Java Reference
In-Depth Information
}, "Thread2").start();
}
And when you run the program, you might get the following output be-
fore the program "hangs":
Thread1 in jareth.hug() trying to invoke cory.hugBack()
Thread2 in cory.hug() trying to invoke jareth.hugBack()
You could get lucky, of course, and have one thread complete the entire
hug without the other one starting. If steps 2 and 3 happened to occur
in the opposite order, jareth would complete both hug and hugBack before
cory needed the lock on jareth . But a future run of the same application
might deadlock because of a different choice of the thread scheduler.
Several design changes would fix this problem. The simplest would be
to make hug and hugBack not synchronized but have both methods syn-
chronize on a single object shared by all Friendly objects. This technique
would mean that only one hug could happen at a time in all the threads
of a single application, but it would eliminate the possibility of dead-
lock. Other, more complicated techniques would enable multiple simul-
taneous hugs without deadlock.
You are responsible for avoiding deadlock. The runtime system neither
detects nor prevents deadlocks. It can be frustrating to debug deadlock
problems, so you should solve them by avoiding the possibility in your
design. One common technique is to use resource ordering. With re-
source ordering you assign an order on all objects whose locks must be
acquired and make sure that you always acquire locks in that order. This
makes it impossible for two threads to hold one lock each and be trying
to acquire the lock held by the otherthey must both request the locks in
the same order, and so once one thread has the first lock, the second
thread will block trying to acquire that lock, and then the first thread
can safely acquire the second lock.
 
Search WWH ::




Custom Search