Java Reference
In-Depth Information
Discussion
The java.util.concurrent package includes Executors ; an Executor is, as its name im-
plies, a class that can execute code for you. The code to be executed can be the familiar Run-
nable or a new interface Callable . One common kind of Executor is a “thread pool.” The
code in Example 22-19 subclasses the main class of the Threaded Web Server from Program:
Threaded Network Server to use a pool of Threads to schedule multiple clients concurrently.
Example 22-19. HttpdConcurrent.java
/**
* HttpConcurrent - Httpd Subclass using java.lang.concurrent
*/
public
public class
class HttpdConcurrent
HttpdConcurrent extends
extends Httpd {
private
private final
final Executor myThreadPool ;
public
public HttpdConcurrent () throws
throws Exception {
super
super ();
myThreadPool = Executors . newFixedThreadPool ( 5 );
}
public
public static
throws Exception {
System . out . println ( "DarwinSys JavaWeb Server 0.1 starting..." );
HttpdConcurrent w = new
static void
void main ( String [] argv ) throws
new HttpdConcurrent ();
iif ( argv . length == 2 && argv [ 0 ]. equals ( "-p" )) {
w . startServer ( Integer . parseInt ( argv [ 1 ]));
} else
else {
w . startServer ( HTTP );
}
w . runServer ();
}
public
public void
void runServer () throws
throws Exception {
while
while ( true
true ) {
final
final Socket clientSocket = sock . accept ();
myThreadPool . execute ( new
new Runnable () {
public
public void
void run () {
new
new Handler ( HttpdConcurrent . this ). process ( clientSocket );
}
});
}
}
}
You can see this program in action in Figure 22-5 .
Search WWH ::




Custom Search