Last week I was reading “Concurrent Programming in Java” from Doug Lea in the train to my work. One of the topics I was reading was chapter 4 “Creating threads” and a distinction was made between 2 different approaches for using threads:
- task-based: when a task needs to be executed asynchronously on a different thread. An example of this is the execution of a batch process started by a Servlet thread when a user pressed a button. After the task is executed, it can be discarded. The Executor was made for task based problems although it lacks some functionality for blocking when a task can’t be processed.
- actor-based: when a thread runs as an automonous process (the actor) and is able to react on events from the environment. An example of an acter based design is a thread that runs a server socket. When a client request is accepted, the server socket processes the request and waits for the next request.
It is possible to combine the actor and task-based styles, e.g. as soon as a socket-request from a client is accepted, the task of processing this request could be executed asynchronously on a different thread (task based) using an Executor to keep the serversocket (actor based) available to other clients.