Deadlocks are annoying
Java’s concurrency model provides a sophisticated menu of ways in which to shoot yourself in the foot. Many styles and many variations are available. To give a taste of some of the delicacies on offer, here’s the essence of a problem I found in some code I’d written recently.
Let thread one perform the tasks:
- lock C
- wait for event 1
- unlock C
- lock C
- wait for event 2
- unlock C
Let thread two perform the tasks:
- signal event 1
- lock C
- unlock C
- signal event 2
When we were trying to pin down the issue, we found that the code would run through to the end about 10% of the time. The other runs locked up with thread one blocked at step 5, and thread two at step 2.
Java doesn’t make any promises about fairness: specifically, thread one’s release of the lock before reacquiring the same lock need not cause a thread switch, even when the runtime knows there’s another thread waiting for that lock.
There are solutions: both STM and shared-nothing message passing are models much easier to reason about. Let’s hope future revisions to the Java system raise the level of discourse.
8 comments June 18th, 2007 tonyg