Global Positioning System Reference
In-Depth Information
11.7.2
Handling Multiple Server Threads
If the ROServer's identify method were synchronized , one client could
block the identification of other clients. One solution to this timing problem
is to create a deferred thread to take care of the remote client call and
immediately continue inside the identify method.
The DeferredThread could be added to the server (object) as a private
class:
private class DeferredThread extends Thread
{
DeferredThread( Runnable r ) {
super(r);
setDaemon(true);
}
public void run() {
try { Thread.sleep(1000); } // wait a second ...
catch (InterruptedException e) {}
super.run();
// ... and execute client call
}
}
Setting the thread as a daemon is a precaution to allow the server to shut
down while clients are still trying to identify themselves.
By using the thread to call the client method, the server's identication
method gets rid of the client call and can return its response.
After a
second, the client can be identified for any duration:
DeferredThread getClientID = new DeferredThread(
new Runnable() {
public void run() // wrap client call in thread
{ candidate.getIdentity(); }});
getClientID.start();
// submit client call ...
...
// ... and immediately continue
The performance drawback of this approach is the creation of a new
thread for every method call. Instead of creating a deferred thread the Java
library has a java.util.Timer , a facility for threads to schedule tasks for fu-
ture execution in a background thread as well as a java.util.TimerTask , a
task that can be scheduled for one-time or repeated execution by a Timer.
The advantage of the timer utility is the one-time creation of a thread,
which will stay alive as long as the timer is working. This built-in mech-
anism could be used as the base element of a more complex job scheduler
to take care of many server processes. For a small number of clients and
methods, this solution works fine. A server developer has to be aware
that there are probably more threads running than he can actively know.
Obviously, a GUI, like Swing, uses internal threads; RMI uses threads to
marshal (pack) and unmarshal (unpack) objects, etc.
 
Search WWH ::




Custom Search