27.10. Programming Exercises

 
[Page 803 ( continued )]

24.15. Avoiding Deadlocks

Sometimes two or more threads need to acquire the locks on several shared objects. This could cause a deadlock , in which each thread has the lock on one of the objects and is waiting for the lock on the other object. Consider the scenario with two threads and two objects, as shown in Figure 24.25. Thread 1 has acquired a lock on object1 , and Thread 2 has acquired a lock on object2 . Now Thread 1 is waiting for the lock on object2 , and Thread 2 for the lock on object1 . Each thread waits for the other to release the lock it needs, and until that happens neither can continue to run.

Figure 24.25. Thread 1 and Thread 2 are deadlocked.

Deadlock is easily avoided by using a simple technique known as resource ordering . With this technique, you assign an order on all the objects whose locks must be acquired and ensure that each thread acquires the locks in that order. For the example in Figure 24.25, suppose that the objects are ordered as object1 and object2 . Using the resource ordering technique, Thread 2 must acquire a lock on object1 first, then on object2 . Once Thread 1 acquires a lock on object1 , Thread 2 has to wait for a lock on object1 . So Thread 1 will be able to acquire a lock on object2 and no deadlock will occur.

 


Introduction to Java Programming-Comprehensive Version
Introduction to Java Programming-Comprehensive Version (6th Edition)
ISBN: B000ONFLUM
EAN: N/A
Year: 2004
Pages: 503

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net