Threaded Network Server
Problem
You want a network server to be multithreaded.
Solution
Either create a thread when you accept a connection, or pre-create a
pool of threads and have each wait on the accept( )
call.
Discussion
Networking (see Chapter 15 through Chapter 17) and threads are two very powerful APIs that are a standard part of the Java platform. Used alone, each can increase the reach of your Java programming skills. A common paradigm is a threaded network server, which can either preallocate a certain number of threads, or can start a new thread each time a client connects. The big advantage is that each thread can block on read, without causing other client threads to delay.
One example of a threaded
socket server was discussed in
Section 16.5; another is shown here. It seems to be some kind of rite (or
wrong) of passage for Java folk to write a web server entirely in
Java. This one is fairly small and simple; if you want a full-bodied
flavor, check out the
Apache Foundation’s Apache
(written in C) and Tomcat (pure Java) servers, or the
World Wide Web
Consortium’s jigsaw
server. The main program
of mine constructs one instance of class Httpd
.
This creates a socket and waits for incoming clients in the
accept( )
method. Each time there is a return from
accept( )
, we have another client, so we create a
new thread to process that client. This happens in the main( )
and runserver( )
methods, which are
near the beginning of Example 24-11.
Example 24-11. Httpd.java
/** * ...
Get Java Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.