http://gee.cs.oswego.edu
Scalable IO in Java
Doug Lea
State University of New York at Oswego
dl@cs.oswego.edu
http://gee.cs.oswego.edu
http://gee.cs.oswego.edu
Outline
"
Scalable network services
"
Event-driven processing
"
Reactor pattern
Basic version
Multithreaded versions
Other variants
"
Walkthrough of java.nio nonblocking IO APIs
http://gee.cs.oswego.edu
Network Services
"
Web services, Distributed Objects, etc
"
Most have same basic structure:
Read request
Decode request
Process service
Encode reply
Send reply
"
But differ in nature and cost of each step
XML parsing, File transfer, Web page
generation, computational services, ...
http://gee.cs.oswego.edu
Classic Service Designs
client
client
client
Server
read
decode
compute
encode
send
read
decode
compute
encode
send
handler
handler
read
decode
compute
encode
send
handler
Each handler may be started in its own thread
http://gee.cs.oswego.edu
Classic ServerSocket Loop
class Server implements Runnable {
public void run() {
try {
ServerSocket ss = new ServerSocket(PORT);
while (!Thread.interrupted())
new Thread(new Handler(ss.accept())).start();
// or, single-threaded, or a thread pool
} catch (IOException ex) { /* ... */ }
}
static class Handler implements Runnable {
final Socket socket;
Handler(Socket s) { socket = s; }
public void run() {
try {
byte[] input = new byte[MAX_INPUT];
socket.getInputStream().read(input);
byte[] output = process(input);
socket.getOutputStream().write(output);
} catch (IOException ex) { /* ... */ }
}
private byte[] process(byte[] cmd) { /* ... */ }
}
}
Note: most exception handling elided from code examples