Threaded Handlers
The Motivation:
    Imagine a client connected to a server. Messages are flowing from the server to the client and the client must process these messages immediately - any delay in handling one message might cause other messages to be missed or handled too late to be useful. Each of the messages directs the client to perform some task. Suppose the tasks are lengthy. Then the client has no choice but to fork a "handler" of the process every time a message is received so it can immediately be ready for the next message. A fork in this case means a thread is assigned to the process and the process is run in the background concurrently with other processes.
The Problem:
    There are two Java files that illustrate the problem and the solution. The file implements a server (class SingleServer) and a client (class SingleClient). The class SingleFrame creates a server object and a client object when its JButton is pressed. Both objects are threaded. The server's thread starts 1 second before the client's so it has ample time to begin listening for a client connection request. When the client starts it connects with the server, enters an infinite while loop and begins listening to the server messages via readLine. Every message received in reported in the client's JTextArea. The client responds to a message by creating a SingleHandler object and invoking its task() method. The method takes 2.5 seconds to complete and its progress is reported in the applet's JTextArea along with a sequence number id to help identify which task invocation is responding to which message. The server sends messages at the rate of 1 per second (these are reported in the server's JTextArea). Therefore, messages get backed up. After several seconds the server's JTextArea shows considerably many messages have been sent while the client's JTextArea shows only a few have been handled. This is bad for the Checkers game because if the Monitor does not see a response to its "alive" request in less than a second it assumes the client is no longer registered. Try this applet.
The Solution:
    The solution is to assign a thread to each handler. This is shown in file Now when a message is received by the client it forks a handler to process the request. Although the handler takes 2.5 seconds to complete, it runs simultaneously with many other processes. See the comments for the two places that these files differ. Try this applet to see the difference in performance.