| ||||
Copyright 1999 Sams Publishing |
|
When Multiple Threads Might Not Be Good |
Its not always a good idea to add more threads to the design of a program. Threads are not free; they carry some resource overhead. |
Each Thread object that is instantiated uses memory resources. In addition to the memory used by the object itself, each thread has two execution call stacks allocated for it by the JavaVM. One stack is used to keep track of Java method calls and local variables . The other stack is used to keep track of native code (typically, C code) calls. |
Each thread also requires processor resources. Overhead is inherent in the scheduling of threads by the operating system. When one threads execution is suspended and swapped off the processor, and another thread is swapped onto the processor and its execution is resumed, this is called a context switch . CPU cycles are required to do the work of context switching and can become significant if numerous threads are running. |
There is also work involved in starting, stopping, and destroying a Thread object. This cost must be considered when threads are used for brief background tasks . For example, consider the design of an email program that checks for new mail every 5 minutes. Rather than create a new thread to check for mail each time, it would be more efficient to have the same thread keep running and sleep for 5 minutes between each query. |
When adding additional threads to the design of a system, these costs should be considered. |
| |||
Toc |