Use Asynchronous Messaging Wherever Possible
Most remote method calls are synchronous: the calling thread stops and waits for a response from the server. An asynchronous method call is one in which the caller doesn’t wait for a response, or even wait to know if the call succeeded. Instead, the calling thread continues processing.
RMI doesn’t directly support asynchronous calls. Instead, you have to use a background thread to make the call. In Example 6-2, the calling thread creates a command object and drops it off in a background queue for execution. This leaves the calling thread free to immediately resume processing, instead of waiting for a response, as in the following code snippet:
BackgroundCallQueue_backgroundQueue = new BackgroundCallQueueImpl( ); // . . . _backgroundQueue.addCall(new SpecificCallToServer( . . . ));
Example 6-2 is a sample implementation of
BackgroundCallQueue
and
BackgroundCallQueueImpl
.
public interface BackgroundCallQueue { public void addCall(RemoteMethodCall callToAdd); } public class BackgroundCallQueueImpl implements BackgroundCallQueue { private LinkedList _pendingCalls; private thread _dispatchThread; public BackgroundCallQueueImpl ( ) { _stopAcceptingRequests = false; _pendingCalls = new LinkedList( ); _dispatchThread = new Thread(this, "Background Call Queue Dispatch Thread"); _dispatchThread;.start( ); } public synchronized void addCall(RemoteMethodCall callToAdd) { _pendingCalls.addCall( ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access