Java Reference
In-Depth Information
An example of using the new locking classes is shown in the “Creating Our Logical
Reserve Methods” section of Chapter 5, and further thoughts are presented in the same
chapter, in the “Discussion Point: Multiple Notification Objects” section.
To ensure that a lock is released, we highly recommend that you place the call to unlock
in a finally block as demonstrated earlier.
Regardless of whether you use synchronized blocks or the new concurrency classes, the
same rules of thread safety apply.
Locking Summary
Object locks and locks on the member variable within the object do not interact in any way.
That is, synchronizing an object does not lock member variables of that object. Nor does syn-
chronizing a member variable lock the object that owns that variable. Threads that own locks
on different objects can run concurrently as long as they do not also share a lock on a com-
mon object. In addition, locking a class does not lock instances of that class. Unsynchronized
access to member variables can violate thread safety.
Understanding Thread Safety
Threading presents unique logical pitfalls, which can often be reached unexpectedly and
seemingly randomly. In this section, we define some of the more common pitfalls and offer
advice on ways to avoid them. The following subsections explain what thread safety is and
the sorts of horrors it helps to prevent.
Deadlocks
Deadlocks occur when threads are blocked forever, waiting for a condition that cannot occur.
Deadlock is like a cartoon where Daffy Duck and Bugs Bunny are stranded on an island. Daffy
has a can of food, and Bugs has a can opener. Daffy won't give up the food until he gets the can
opener, and Bugs won't give up the can opener until he gets some food. They are deadlocked.
In Listing 4-8, you can see that thread1 acquires a lock on lock1 but needs lock2 . thread2
has acquired a lock on lock2 and needs to acquire lock1 . Neither thread will allow the other
thread to progress, nor will it progress itself. This is deadlock. Figure 4-7 shows the output.
Listing 4-8. Deadlock Example
1 public class DeadlockExample {
2 /**
3 * Entry point to the application. Creates 2 threads that will deadlock.
4 */
5 public static void main(String args[]) {
6 DeadlockExample dle = new DeadlockExample();
7
8 Object lock1 = "Lock 1";
9 Object lock2 = "Lock 2";
10
Search WWH ::




Custom Search