Java Reference
In-Depth Information
Figure 4-8. Output from the race condition example
It is clear here that there is no consistency in terms of who gets access to the server. This
could be perfectly all right, or it could be catastrophic. It all depends on context. While it is not
necessary to resolve every race condition in order to achieve thread safety, it is important to be
aware of them.
Starvation
Starvation occurs when a thread never gets a chance to run. Its most common manifestation
occurs when higher-priority threads keep getting preferential treatment over those with a
lower priority. Imagine that your task requires that you speak to the CTO of your company.
However, every time it seems as if she might be free, a senior executive steps in and takes the
slice of time you were going to use. This could be for very legitimate reasons, but the end
result is that you never get to speak with her (your thread never gets a chance to run).
The example in Listing 4-10 shows a contrived example of three high-priority threads and
one low-priority thread all trying to use the same resource.
Listing 4-10. Starvation Example
1 /**
2 * Demonstrate the concept of a starving thread.
3 */
4 public class StarvationExample {
5 public static void main(String args[]) {
6 // Ensure the main thread competes with the other threads
7 Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
8
Search WWH ::




Custom Search