Java Reference
In-Depth Information
crawl. On the other hand, if the protocol is simple and quick and allows the server to
close the connection when it's through, it will be more efficient for the server to process
the client request immediately without spawning a thread.
The operating system stores incoming connection requests addressed to a particular
port in a first-in, first-out queue. By default, Java sets the length of this queue to 50,
although it can vary from operating system to operating system. Some operating systems
(not Solaris) have a maximum queue length. For instance, on FreeBSD, the default
maximum queue length is 128. On these systems, the queue length for a Java server
socket will be the largest operating-system allowed value less than or equal to 50. After
the queue fills to capacity with unprocessed connections, the host refuses additional
connections on that port until slots in the queue open up. Many (though not all) clients
will try to make a connection multiple times if their initial attempt is refused. Several
ServerSocket constructors allow you to change the length of the queue if its default
length isn't large enough. However, you won't be able to increase the queue beyond the
maximum size that the operating system supports. Whatever the queue size, though,
you want to be able to empty it faster than new connections are coming in, even if it
takes a while to process each connection.
The solution here is to give each connection its own thread, separate from the thread
that accepts incoming connections into the queue. For instance, Example 9-3 is a day‐
time server that spawns a new thread to handle each incoming connection. This prevents
one slow client from blocking all the other clients. This is a thread per connection design.
Example 9-3. A multithreaded daytime server
import java.net.* ;
import java.io.* ;
import java.util.Date ;
public class MultithreadedDaytimeServer {
public final static int PORT = 13 ;
public static void main ( String [] args ) {
try ( ServerSocket server = new ServerSocket ( PORT )) {
while ( true ) {
try {
Socket connection = server . accept ();
Thread task = new DaytimeThread ( connection );
task . start ();
} catch ( IOException ex ) {}
}
} catch ( IOException ex ) {
System . err . println ( "Couldn't start server" );
}
}
private static class DaytimeThread extends Thread {
Search WWH ::




Custom Search