Java’s Executor Framework for Starters

Rishabh Agarwal
5 min readMar 23, 2024
Photo by Markus Spiske on Unsplash

Consider that you are working on a Web-app’s server. A client would make an HTTP/HTTPS request to your server and would expect some data in response. From your server’s perspective, each client request is a task and can be executed independent of another client request if required.

Once the tasks have been identified, you need to think of their execution policy. Should all the tasks be executed in a single thread? Or, should each task spawn a new thread, execute, and kill the thread? Or, should their be some different approach altogether?

Let us say, you ended up with the choice of executing all tasks in a single thread. This is how this code will look like.

class WebServer {
public static void main(String[]args) {
ServerSocket socket = new ServerSocket(80);
while(true) {
Socket connection = socket.accept();
handleRequest(connection);
}
}
}

In the code above, each request is handled by the main thread itself and any new request would have to wait at the socket until earlier requests are all served.

You realised that this is not ideal and would highly impact the availability of your server. Thus, you decided to change the execution policy to ‘spawn a new thread per request’. This is how the code after the execution policy change looks.

--

--

Rishabh Agarwal

Software Developer 2 @ Schrödinger | IIT CSE Graduate - Writes about Software Engineering!