Java Reference
In-Depth Information
becomes ready to run, the virtual machine will sooner or later (and probably sooner)
pause the lower-priority thread to allow the higher-priority thread to run. The higher-
priority thread preempts the lower-priority thread.
The situation when multiple threads of the same priority are ready to run is trickier. A
preemptive thread scheduler will occasionally pause one of the threads to allow the next
one in line to get some CPU time. However, a cooperative thread scheduler will not. It
will wait for the running thread to explicitly give up control or come to a stopping point.
If the running thread never gives up control and never comes to a stopping point and
if no higher-priority threads preempt the running thread, all other threads will starve.
This is a bad thing. It's important to make sure all your threads periodically pause
themselves so that other threads have an opportunity to run.
A starvation problem can be hard to spot if you're developing on a VM
that uses preemptive thread scheduling. Just because the problem
doesn't arise on your machine doesn't mean it won't arise on your
customers' machines if their VMs use cooperative thread scheduling.
Most current virtual machines use preemptive thread scheduling, but
some older virtual machines are cooperatively scheduled, and you may
also encounter cooperative scheduling in special-purpose Java virtual
machines such as for embedded environments.
There are 10 ways a thread can pause in favor of other threads or indicate that it is ready
to pause. These are:
• It can block on I/O.
• It can block on a synchronized object.
• It can yield.
• It can go to sleep.
• It can join another thread.
• It can wait on an object.
• It can finish.
• It can be preempted by a higher-priority thread.
• It can be suspended.
• It can stop.
Inspect every run() method you write to make sure that one of these conditions will
occur with reasonable frequency. The last two possibilities are deprecated because they
have the potential to leave objects in inconsistent states, so let's look at the other eight
ways a thread can be a cooperative citizen of the virtual machine.
Search WWH ::




Custom Search