The Dining Philosophers problem was first presented by Dijkstra in 1965 as an exam exercise for his students.
Each philosopher alternates between thinking (analagous to CPU computation) and eating with shared chopsticks (analagous to accessing a shared IO device like a disc drive).
In the implementation below uses synchronized to acquire the intrinsic lock to the chopstick to its right followed by acquiring the intrinsic lock to the chopstick to its left before eating.
The intristic locks are automatically released when the philosopher is done eating and continues to the thinking in the next iteration of the loop.
class Philosopher:
def exist():
while( true ):
think()
synchronized(rightChopstick)
synchronized(leftChopstick)
eat()
|
|
The documentation for java.util.concurrent.locks.ReadWriteLock states:
A ReadWriteLock maintains a pair of associated locks, one for read-only operations and one for writing. The read lock may be held simultaneously by multiple reader threads, so long as there are no writers. The write lock is exclusive.
V compute(K key, BiFunction<K,V,V> remappingFunction)
V get(Object key)
V put(K key, V value)