Implementing a continuously updating component
In this section, we'll revisit the Server Status component and allow it to periodically update itself. To do this, you'll add the ability to set the refresh rate for the data, as well as add the ability to change or stop the automatic updates. In doing so, we'll need to look at the GWT Timer class, which allows you to trigger timed events.
If you've been following along with us, your Server Status component should be working and have a method that can be called to have it update its information from the server. If you haven't been following with us, here is the basic shell for the Server Status component, which includes a getStatusDataFromServer() method that triggers an RPC call and updates the displayed data:
package org.gwtbook.client;
import java.util.Date; import com.google.gwt.core.client.*; import com.google.gwt.user.client.rpc.*; import com.google.gwt.user.client.ui.*;
public class ServerStatusComponent extends Composite {
public ServerStatusComponent () { }
private void getStatusDataFromServer () { }
In the full version of the Server Status component, the getStatusDataFrom-Server() method is called when the component is first initialized or when an update button is clicked. Next, you'll add a timer to trigger an update as well.
Using the GWT Timer class
The Timer class can be found in the com.google.gwt.user.client package. It provides a no-argument constructor and several methods. The method signatures are as follows:
public abstract class Timer { public abstract void run(); public void schedule(int milliseconds); public void scheduleRepeating(int milliseconds); public void cancel();
The first thing to point out is that the Timer class is abstract, so you must subclass it to be able to use it. You can do this by creating an anonymous class or creating your own specialized timer class. When you implement your class, you need to implement the abstract method, run(), that is called when the timer is triggered. In this example, you create a timer that alerts the user with a "hello" message when a timer event is triggered:
Timer example = new Timer() { public void run () { Window.alert("hello");
To trigger a timer event, you need to set either a one-time event with the sched-ule() method or a recurring event with the scheduleRepeating() method. In the case of schedule(), you specify the number of milliseconds to wait before executing the run() method. The scheduleRepeating() method also takes the number of milliseconds as a parameter, and it repeatedly executes the run() method. The first execution of run() begins in the number of milliseconds specified and then continuously recurs at that same interval.
The cancel() method, as apparent by its name, allows you to stop the timer. Once it's stopped, you may start it again by calling either the schedule() or scheduleRepeating() method. The following example sets the timer for five seconds and then cancels it:
example.schedule(5000); example.cancel(); // just kidding
The next step is to add additional methods to the Server Status component to provide the ability to set the update interval as well as the ability to stop the automatic updates. You'll do this via a schedulable class.
Creating a schedulable class
There are many ways to implement a timer, but you'll use an approach we think is highly reusable. The code not only can be used in the Server Status component, but also applies to any Composite component. It's also possible, with some minor changes, to adapt it to other base classes.
You'll accomplish this by creating a subclass of Composite called UpdateableComposite, shown in figure 11.7, that provides methods for setting and stopping the update timer. Before you start coding, look at the class diagram to see the relationships between the new class and the existing ServerStatusComponent class.
- Figure 11.7 A structural overview of the reusable, updateable-composite
We'll begin by introducing the new UpdateableComposite as a subclass of Composite. UpdateableComposite is an abstract class, meaning that it must be subclassed to use it, and it contains three methods. The startUpdateTimer() method starts the update timer. It allows you to specify the number of seconds between updates; you can use this same method to change the update interval. The update() method is an abstract method and must be implemented by the subclass.
Once you implement UpdateableComposite class, you alter the Server Status component to implement the update() method, and then set the timer (see listing 11.11).
Listing 11.11 Abstract UpdateableComposite class package org.gwtbook.client;
import com.google.gwt.user.client.Timer; import com.google.gwt.user.client.ui.Composite;
public abstract class UpdateableComposite extends Composite {
private Timer timer = null; public abstract void update();
public void startUpdateTimer(int seconds) {
timer = new Timer() { public void run() { update();
timer.scheduleRepeating(seconds * 1000);
public void stopUpdateTimer() {
The implementation is straightforward but is worth some explanation. The class contains a single private field called timer, which holds the Timer object. You need to hold onto a reference to the Timer object so that you can cancel it when stopUpdateTimer() is called. Looking at the stopUpdateTimer() method, you can see that the method calls cancel() on the Timer object and then sets the timer field to null.
The startUpdateTimer() method first checks to see if the timer field is null. If it isn't null, this is a sign that it has already been started. The method responds by calling stopUpdateTimer() to cancel the existing timer. This allows you to use startUpdateTimer() to change the interval period without having to worry about stopping the existing timer. The method then goes on to create a Timer instance. You're creating the Timer as an anonymous class, which prevents external clients of this class from being able to control the timer directly. In the timer's run() method, you call the abstract method update(). It will be left up to the subclasses of UpdateableComposite to determine what the update() method does.
With the UpdateableComposite complete, the only thing left to do is alter the Server Status component to take advantage of the scheduling capabilities:
public class ServerStatusComponent extends UpdateableComposite
public void update() {
getStatusDataFromServer();
The only change is that you now extend UpdateableComposite instead of Composite directly, and you implement the update() method. The update() method, in turn, calls the private method getStatusDataFromServer(), which you created before triggering an RPC call to the server. In projects other than the Server Status component, you can include whatever code is required to update the component in the update() method.
With this mechanism in place, you can now easily create and schedule updates for the component. The code to do this for the Server Status component is here, but it will be essentially the same for any custom component that subclasses UpdateableComposite:
ServerStatusComponent serverStatus = new ServerStatusComponent();
serverStatus.startUpdateTimer(6 0);
In summary, using the GWT Timer class, it's easy to schedule a piece of code to execute on a schedule. The concepts for doing this are the same no matter if you're using a timer to schedule polling of the server or updating a display. In either case, it's always a good idea to think through the design and use the tools that Java provides to create reusable code. The UpdateableComposite is just one example.
Now that we've explored timers and, in conjunction, the concept of polling, it's time to look at how you can emulate server-push and push events to the client browser.
11.2.3 Emulating server-push by blocking server threads
As we briefly mentioned earlier, no true server-push is available to browsers, meaning the server can't send data to the browser without the browser requesting it. The reasons are security and lack of a standard. To accommodate for this lack of functionality, there are several schemes for emulating server-push. In this section, we'll discuss and implement one such variation called blocking server threads.
From a high level, RPC involves a client browser requesting data from a server. The server then processes the request and returns a result. Not only is this how browser-based RPC works, but it's also how web pages are served. With blocking server threads, you add one small alteration: You hold up the processing on the server until data is available to process. It's similar to a company with poor customer service—you end up waiting on hold until there is someone to talk to you.
To help understand how this works, figure 11.8 provides a visual comparison between polling and blocking server threads.
- Figure 11.8 A visual comparison of server polling and the blocking-threads technique
In figure 11.8 you can see that when you use polling, the browser handles the orchestration by calling the server every 20 seconds. With blocking, the server becomes the conductor, placing the request on hold until it needs to process the request. Another important difference is that with blocking, you have an almost constant connection between the client and the server.
A web-based chat client is the classic example of the need for blocking server threads, and we'll use this type of application as our example. You won't build a complete component because doing so would require covering a lot of the same topics we've already discussed; but we'll explain the few changes required to make it work. We'll start with the code required on the client and then look at what changes are needed on the server.
Implementing blocking on the client
When you implement the client side of blocking server threads, there is little that you need to do. The only requirement is that each time you get a response from the server, you need to initiate a new request. Take the following AsyncCallback implementation for example. We've removed the implementation details, but notice that it calls the method getDataFromServer() on both success and failure:
class ChatPanelUpdater implements AsyncCallback {
public void onFailure (Throwable caught) { getDataFromServer();
public void onSuccess (Object result) { getDataFromServer();
You'd need to define getDataFromServer(); the only requirement is that this method triggers another RPC request. In the Server Status component, the method getStatusDataFromServer() serves the same purpose.
With this one minor change, we can turn our attention to the more interesting aspects of blocking server threads on the server.
Implementing blocking on the server
Implementing the server portion of a blocking RPC server can be done the same way you block any Java thread: by issuing a sleep command. When you issue a sleep command to the JVM, it stops processing that specific thread of execution for some amount of time. Once the sleep time is finished, the thread wakes up and continues processing. Issuing a sleep command involves a single statement. The method Thread.sleep() takes a number of milliseconds to sleep; passing 1000 to the method causes the thread to sleep for one second:
Thread.sleep(1000);
For our purposes, you need to do more than just block the thread for some amount of time. You need to first determine whether you should process the request, which in the case of a chat application is when you have a message that you want to send the user. On the other hand, if you don't have a message to send, you should put the thread to sleep for a short period of time. Once the thread wakes up, you check again whether you should process the request. To do so, you use a loop similar to this:
public List getMessages ()
List result = new ArrayList();
Thread.sleep(1000);
} catch (InterruptedException ignore) {
return result;
You use the while(true) loop to create an endless loop, and at the end of the loop, you use Thread.sleep() to sleep for one second. Prior to sleeping, you check to see if you can process the request by calling canProcess(); if you can, you call process() to get the result of the RPC call and then break out of the while loop. The try statement catches an InterruptedException, which could result from the call to Thread.sleep() —for example, if the application server was being shut down.
This loop is fine, but what happens if the user closes their browser or navigates to a different web page? Unfortunately, you don't have a good way to be notified of these events, so potentially a thread could loop forever even though the browser client is no longer present. To solve this problem, you need to introduce a timeout (see listing 11.12).
Listing 11.12 Blocking threads example with the introduction of a timeout public List getMessages () {
List result = new ArrayList();
long timeout = System.currentTimeMillis() + (30 * 1000);
if (System.currentTimeMillis() > timeout) { break;
Thread.sleep(1000);
} catch (InterruptedException ignore) { }
return result;
To the original example, you added a timeout value: You set the value to the current time in milliseconds and add 30 seconds to that value. You also added a check, and, if the current time exceeds the timeout value, it breaks the loop. The timeout value you use depends on your specific project, but in most cases 30 seconds is sufficient to keep the number of requests down while removing stale connections quickly.
The exact implementation of canProcess() and process() depends a lot on the purpose of the method. For example, with the chat application, you'll likely have a queue of messages for each user of the system, in which case canProcess() returns true if any messages are in the queue for that user. The process() method then returns the list of messages and clears out the queue, or marks the messages in the queue as being delivered.
Now that we've shown how you can easily implement polling, let's turn our attention to a completely different, although equally important, topic: how to create custom serialization routines for your objects.
Post a comment