Using TCPServer with AsyncInputStreams

Let’s modify our ServerHandler class to read requests from clients in an asynchronous manner:

import java.net.*;
import java.io.*;

public class ServerHandler extends TCPServer {
    public void run(Socket data) {
        try {
            InputStream is =
                new AsyncInputStream(data.getInputStream());
            OutputStream os = data.getOutputStream();

            // Process the data socket here. 
        } catch (Exception e) {}
    }
}

With a single line change to our ServerHandler class, we are now reading from the client in an asynchronous manner. We also practically doubled the number of threads started to provide this service. But from examining the source code, there is no indication that even one thread is started, much less two threads per client connected (plus an additional thread to handle the accept() method).

Get Java Threads, Second Edition 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.