Quick revision
The short answer
We open a ServerSocket on a port and loop on accept(), which returns a new Socket for each client, and hand each socket to its own thread that reads lines from the input stream and writes them back to the output stream, with try-with-resources closing the socket and streams. A read timeout set with setSoTimeout stops idle clients from holding a thread forever. On Java 21 and later, we replace the thread pool with Executors.newVirtualThreadPerTaskExecutor(), so every client gets a cheap virtual thread and simple blocking code scales to many thousands of connections.
What to remember
In this answer, we built a blocking TCP echo server: a ServerSocket loops on accept() to get a Socket per client, each client is handled on its own thread that reads lines and writes them back, try-with-resources closes the socket and streams on every path, and setSoTimeout stops idle clients from hanging a thread. On Java 21 and later, we swap the bounded platform pool for Executors.newVirtualThreadPerTaskExecutor(), so each client gets a cheap virtual thread while the code stays simple and blocking.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
We open a ServerSocket on a port and loop on accept(), which returns a new Socket for each client, and hand each socket to its own thread that reads lines from the input stream and writes them back to the output stream, with try-with-resources closing the socket and streams. A read timeout set with setSoTimeout stops idle clients from holding a thread forever. On Java 21 and later, we replace the thread pool with Executors.newVirtualThreadPerTaskExecutor(), so every client gets a cheap virtual thread and simple blocking code scales to many thousands of connections.
Background to this question
An echo server is the smallest program that shows how a TCP server really works: listening, accepting, reading, writing and closing. It is also a good test of whether we can write correct resource handling and concurrency without a framework. And since Java 21, it is the clearest demonstration of what virtual threads change. In this answer, we will recap the socket classes, write a version that serves one client at a time and see its problem, make it concurrent with a thread per client, add timeouts and correct closing, and then switch to virtual threads.
1A Quick Recap of ServerSocket and Socket
TCP is a protocol for reliable, ordered byte streams between two programs. In Java, a ServerSocket listens on a port, for example 7000, and its accept() method blocks until a client connects, then returns a Socket that represents that one connection. The Socket gives us an InputStream to read what the client sends and an OutputStream to write back. Both are blocking: read waits until data arrives, and write waits until the data is handed to the operating system.
Blocking is what makes the code simple, and also what makes concurrency necessary. While a thread is waiting in read() for one client, it cannot do anything for another.
2A First Version That Serves One Client at a Time
The simplest server accepts a client, echoes until the client disconnects, and only then accepts the next one.
It works for one client, but notice the second terminal. The main thread is stuck inside the inner loop, waiting in readLine() for the first client, so it never returns to accept(). The second client's connection is queued by the operating system in the listen backlog, but nobody reads from it until the first client leaves.
3Serving Several Clients With a Thread per Client
The classic fix is to keep the main thread doing only one thing, accepting, and to give each accepted socket to another thread. Before Java 21, we would use a bounded pool of platform threads so that a flood of clients cannot create unlimited threads.
8 messages in order. Play them, or step through them one at a time.
The main thread only accepts; each client has its own worker.
A few details matter. try (client; ...) uses the Java 9 form of try-with-resources with an existing variable, so the socket is closed on every path, including exceptions; closing the socket also closes its streams. readLine() returns null when the client closes its side, which ends the loop and closes ours. PrintWriter with autoflush true sends each line immediately; without the flush the client would wait for a buffer to fill. And setSoTimeout makes a blocking read throw SocketTimeoutException after 30 seconds of silence, so an idle or vanished client cannot hold a thread forever.
4The Limit of Platform Threads
Each platform thread is an operating system thread with its own stack, often reserved at 1 MB or so, and switching between thousands of them is expensive. That is why we capped the pool at 200. But with a cap, client 201 waits in the queue even if the 200 connected clients are all idle. Before virtual threads, the escape was non-blocking I/O with selectors, through NIO or a framework like Netty, which scales well but turns simple loops into callbacks and state machines.
5What Changes on Java 21: Virtual Threads
Java 21 made virtual threads a standard feature. A virtual thread is a thread managed by the JVM rather than the operating system. When it blocks on socket I/O, the JVM parks it and frees the underlying carrier thread to run another virtual thread, so blocking costs almost nothing. We can create one per client, even hundreds of thousands, and keep the simple blocking code.
Notice that only the executor changed. There is no pool size to tune, because virtual threads are not a scarce resource; what limits us now are real resources such as file descriptors, memory for buffers, and the services our handler calls, so a real server would still cap connections deliberately, for example with a Semaphore. On Java 21 to 23, a virtual thread blocking inside a synchronized block could pin its carrier thread; Java 24 removed that limitation for synchronized, so on Java 25 it is no longer a concern for code like this.
6Follow-up questions
Why not create a new Thread for each client without an executor?
With platform threads, unbounded thread creation lets a burst of clients exhaust memory, which is why a bounded pool was the rule. With virtual threads, Thread.ofVirtual().start(...) per client is fine, and the executor is just a convenient way to do the same with an AutoCloseable that waits for tasks on shutdown.
What does the backlog of a ServerSocket do?
It is the queue of connections that the operating system has completed but our code has not yet accepted. new ServerSocket(port, backlog) sets a hint for its size; if our accept loop is slow and the queue is full, new connections are refused or time out. A fast accept loop that hands work off immediately keeps it short.
Why set a timeout if virtual threads are cheap?
Because each idle connection still holds a socket and file descriptor, and clients that vanish without closing, for example after a network failure, would otherwise stay forever. Timeouts are about resources and correctness, not only thread cost.
7Conclusion
In this answer, we built a blocking TCP echo server: a ServerSocket loops on accept() to get a Socket per client, each client is handled on its own thread that reads lines and writes them back, try-with-resources closes the socket and streams on every path, and setSoTimeout stops idle clients from hanging a thread. On Java 21 and later, we swap the bounded platform pool for Executors.newVirtualThreadPerTaskExecutor(), so each client gets a cheap virtual thread while the code stays simple and blocking.
Open with
I would create a ServerSocket on a port, say 7000, and loop forever on accept, which blocks until a client connects and returns a Socket for that connection.
Then, if they want more
The main thread should only accept, so I hand each socket to another thread straight away; otherwise the server is stuck reading from the first client and nobody else gets served. In the handler I use try-with-resources on the socket itself and on a BufferedReader and an autoflushing PrintWriter around its streams, so everything is closed on every path.
I read lines until readLine returns null, which means the client closed its side, and write each one back. I also call setSoTimeout, say 30 seconds, so a silent or vanished client makes the read throw SocketTimeoutException instead of holding the thread forever.
Before Java 21 I would use a bounded fixed thread pool, maybe 200 threads, because platform threads are expensive, which means client 201 waits even if the others are idle. On Java 21 or later I would change just one line: use Executors.newVirtualThreadPerTaskExecutor in try-with-resources.
Each client gets its own virtual thread, blocking reads just park the virtual thread and free the carrier, so the simple blocking code scales to many thousands of connections. I would still cap connections deliberately and keep the timeouts, because sockets and memory are still finite.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- Java 21, Java 19, Java 24, Java 25
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- The Java Language Specification, Java SE 21, Java SE 21 API documentation
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Write a minimal blocking TCP echo server with ServerSocket that can serve several...": https://scrivio-interview-library.netlify.app/java/networking/d8e27a1a23/