12
I have been tested fair and non fair disciplines via RentrantLock. I wrote a small program that simulates dinning philosophers.
Each philospher has left and right fork which are ReentrantLocks. I have simulated 1000 times act of thinking and eating:
for (int i = 0; i < ACT_TIMES; i++) {
act();
}
where act is
private void act() {
think();
eat();
}
Think is not interesting it just sleeps for some amount of time. Here is eat method
private void eat() {
try {
if (left.tryLock(0, TimeUnit.MILLISECONDS)) {
if (right.tryLock(0, TimeUnit.MILLISECONDS)) {
log("eating");
eatCount++;
try {
Thread.sleep(EAT_TIME);
} catch (InterruptedException e) {
} finally {
left.unlock();
right.unlock();
}
} else {
left.unlock();
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Main method:
Lock[] forks = new Lock[5];
for (int i = 0; i < forks.length; i++) {
forks[i] = new ReentrantLock();
}
Philosopher p1 = new Philosopher(0, forks[1], forks[0]);
Philosopher p2 = new Philosopher(1, forks[2], forks[1]);
Philosopher p3 = new Philosopher(2, forks[3], forks[2]);
Philosopher p4 = new Philosopher(3, forks[4], forks[3]);
Philosopher p5 = new Philosopher(4, forks[0], forks[4]);
ExecutorService exec = Executors.newFixedThreadPool(5);
exec.submit(p1);
exec.submit(p2);
exec.submit(p3);
exec.submit(p4);
exec.submit(