The Thread-Per-Message design pattern is the simplest concurrency technique strategy wherein a thread is created for each incoming request. The This design pattern is only productive when the benefits of creating a new thread to handle each request should outweigh the corresponding thread creation overheads. This design strategy is generally recommended over sequential executions for of time consuming, I/O bound, session based or isolated tasks.
Wiki Markup |
---|
OnAt the othersame handtime, this theredesign canpattern behas several pitfalls, ofincluding this design strategy such asoverheads of thread -creation overhead in case of frequent or recurring requests, significant processing overheadand scheduling, task processing, resource exhaustionallocation (leading to {{OutOfMemoryError}})and deallocation, threadand schedulingfrequent and context switching overhead \[[Lea 00|AA. Java References#Lea 00]\]. Furthermore, an attacker can cause a denial of service by overwhelming the system with too many requests, all at once. Instead of degrading gracefully, the system becomes unresponsive |
, resulting in an availability issue. From the safety point of view, one component can potentially exhaust all resources because of some intermittent error, starving all other components. |
Thread pools allow the system to service as many requests as it can comfortably sustain, instead of terminating all services when faced with a deluge of requests. From the safety point of view, it is possible for one component to exhaust all resources because of some intermittent error, starving all others from using them.Thread Pools They overcome these issues because the maximum number of worker threads that can be initiated and executed concurrently can be suitably controlled. Every worker accepts a Runnable
object from a request or Callable<T>
task and stores it in a temporary Channel
like such as a buffer or a queue until resources become available. Because threads are in a thread pool can be reused and can be efficiently added to and removed from the Channel
, most of the thread creation overhead is also eliminatedthere is minimal thread life-cycle management overhead.
Noncompliant Code Example
This noncompliant code example demonstrates the Thread-Per-Message design that pattern which fails to provide graceful degradation of service. The class RequestHandler
provides a public static factory method so that callers can obtain its instance. Subsequently, the handleRequest()
method is used to handle each request in its own thread.
...