Java Reference
In-Depth Information
Note The exact output varies with each running of this application, as thread priorities and scheduling
cannot be guaranteed. However, in the majority of executions of this application, you will note that the
StarvationThread either does not run at all, or runs far fewer times than the other three threads. In the
cases where the StarvationThread does run, it is almost always after the other three threads have
completed.
Understanding Atomic Operations
Atomic operations are indivisible. A thread will not be swapped out while in the middle of an
atomic operation. In practical terms, the only naturally occurring atomic operations in Java
are assignments. For example,
x = 45;
is an atomic operation when x is an int . The only exceptions to this rule are assignments
involving doubles and longs. Those are not atomic.
Operations involving longs and doubles are essentially two operations, because longs and
doubles are so big. The first part of the operation sets the high 32 bits, and the next part sets
the low 32 bits. This means that mid-assignment to a long or double variable, your thread
could be sliced out.
Your thread consists of a number of programmatic statements. These in turn consist of
atomic statements. Your thread of execution could be swapped out anywhere, except while
Java is in the middle of an atomic statement. For example:
1 x = 7;
2 y = x++;
is really
1 x =7;
2a int temp = x + 1;
2b x = temp;
2c y=x;
Assume x , y , and z are class member variables. A thread swap between lines 2a and 2b
could lead to unexpected results, for example, if the thread that has swapped in changes the
value of x to, say, 13. You could end up with the bizarre result of y being 13 (and a headache).
Of course, this problem would not exist if x , y , and z were local method variables, because
then no other method could have access to them.
By wrapping your method in a synchronized block, you are effectively treating the entire
method as a single atomic operation, as far as other threads' clients of that object are con-
cerned. Even if another thread swaps in before your method is done executing, as long as the
thread calls methods on your object that are synchronized, you are guaranteed that corrup-
tions such as the previous one will not occur, because those methods will not execute until
your method returns.
The example in Listing 4-11 shows a contrived example of 10 threads yielding at an inop-
portune time, causing invalid results.
Search WWH ::




Custom Search