Java Reference
In-Depth Information
6.1.2. Explicitly Creating Threads for Tasks
A more responsive approach is to create a new thread for servicing each request, as shown in
ThreadPerTaskWebServer in Listing 6.2 .
Listing 6.2. Web Server that Starts a New Thread for Each Request.
ThreadPerTaskWebServer is similar in structure to the single-threaded version—the
main thread still alternates between accepting an incoming connection and dispatching the
request. The difference is that for each connection, the main loop creates a new thread to pro-
cess the request instead of processing it within the main thread. This has three main conse-
quences:
Task processing is offloaded from the main thread, enabling the main loop to resume
waiting for the next incoming connection more quickly. This enables new connec-
tions to be accepted before previous requests complete, improving responsiveness.
Tasks can be processed in parallel, enabling multiple requests to be serviced simul-
taneously. This may improve throughput if there are multiple processors, or if tasks
need to block for any reason such as I/O completion, lock acquisition, or resource
availability.
Task-handling code must be thread-safe, because it may be invoked concurrently for
multiple tasks.
Search WWH ::




Custom Search