Java Reference
In-Depth Information
public final static int PORT = 13 ;
public static void main ( String [] args ) {
ExecutorService pool = Executors . newFixedThreadPool ( 50 );
try ( ServerSocket server = new ServerSocket ( PORT )) {
while ( true ) {
try {
Socket connection = server . accept ();
Callable < Void > task = new DaytimeTask ( connection );
pool . submit ( task );
} catch ( IOException ex ) {}
}
} catch ( IOException ex ) {
System . err . println ( "Couldn't start server" );
}
}
private static class DaytimeTask implements Callable < Void > {
private Socket connection ;
DaytimeTask ( Socket connection ) {
this . connection = connection ;
}
@Override
public Void call () {
try {
Writer out = new OutputStreamWriter ( connection . getOutputStream ());
Date now = new Date ();
out . write ( now . toString () + "\r\n" );
out . flush ();
} catch ( IOException ex ) {
System . err . println ( ex );
} finally {
try {
connection . close ();
} catch ( IOException e ) {
// ignore;
}
}
return null ;
}
}
}
Example 9-4 is structured much like Example 9-3 . The single difference is that it uses a
Callable rather than a Thread subclass, and rather than starting threads it submits these
callables to an executor service preconfigured with 50 threads.
Search WWH ::




Custom Search