Java Reference
In-Depth Information
The following code instantiates one MyStack object, which is shared between two
Pusher threads. The two threads run and each pushes fi ve int s onto the MyStack object:
MyStack stack = new MyStack();
Pusher one = new Pusher(stack);
Pusher two = new Pusher(stack);
one.start();
two.start();
try {
one.join();
two.join();
}catch(InterruptedException e) {}
System.out.println(stack.toString());
The main thread calls join on the two Pusher threads, which causes the main thread to
wait until both Pusher threads run to completion. Then the toString method displays the
contents of the values array. Because the code uses threads, the output varies depending on
the environment that the code executes in, but here is a sample output:
1 2 2 3 3 4 4 5 5 0
Notice that the contents of this array are not consistent with the logic of the program.
Each Pusher thread pushed the numbers 1 through 5 onto the stack, so there should appear
two 1 s, two 2 s, and so on. Instead, there is only one 1 on the stack and a 0 appears at the
end, so only nine elements were actually pushed on the stack.
The problem is that when an int is pushed onto the stack, both the values array and the
index need to be updated in an atomic manner (without being interrupted). By yielding in
the middle of a push, the stack is left in an invalid state. When the 1 is pushed on the stack
by the fi rst thread, the following statement (from line 7 of MyStack ) executes:
values[0] = 1;
Before the thread can increment index by 1 , it yields to the second thread, which
immediately pushes a 1 onto the stack also. But index is still 0 , so the second thread
executes the same statement:
values[0] = 1;
At this point in the program, the array data has been corrupted because both threads
pushed a 1 onto the fi rst element in the stack. The problem is that the second thread should
not have been allowed to invoke the push method of the MyStack object while the fi rst
thread was in the middle of a push. These two threads need to be synchronized, which we
will fi x in the next section, but fi rst I need to discuss the details of an object's monitor lock.
Search WWH ::




Custom Search