This is a nice lesson on why you should synchronize access to all shared mutable data. Your Chopstick
has a field that is not volatile but is accessed by multiple threads via inUse
. The only spot where inUse
is being referenced without synchronization is at
while (_leftChopstick.inUse() || _rightChopstick.inUse())
Without synchronization rightChopstick.inUse()
can return values that are unexpected via data race. As a result all threads that are hanging are stuck at
_leftChopstick.wait();
If you synchronize inUse
you should have it finishing correctly. Also I would highly recommend synchronizing on all the methods in Chopstick