What is deadlock?

Deadlock occurs when two threads are blocked, with each waiting for the other's lock. Neither
can run until the other gives up its lock, so they'll sit there forever.
Example:
public class DeadlockRisk {
2. private static class Resource {
3. public int value;
4. }
5. private Resource resourceA = new Resource();
6. private Resource resourceB = new Resource();
7. public int read() {
8. synchronized(resourceA) { // May deadlock here
9. synchronized(resourceB) {
10. return resourceB.value + resourceA.value;
11. }
12. }
13. }
14.
15. public void write(int a, int b) {
16. synchronized(resourceB) { // May deadlock here
17. synchronized(resourceA) {
18. resourceA.value = a;
19. resourceB.value = b;
20. }
21. }
22. }
23. }
Assume that read() is started by one thread and write() is started by another.
If there are two different threads that may read and write independently, there is a
risk of deadlock at line 8 or 16. The reader thread will have resourceA, the writer
thread will have resourceB, and both will get stuck waiting for the other.
Code like this almost never results in deadlock because the CPU has to switch
from the reader thread to the writer thread at a particular point in the code, and the
chances of deadlock occurring are very small. The application may work fine 99.9
percent of the time.
The preceding simple example is easy to fix; just swap the order of locking for
either the reader or the writer at lines 16 and 17 (or lines 8 and 9).

No comments:

Post a Comment