undefined

Open Source Your Knowledge, Become a Contributor

Technology knowledge has to be shared and made accessible for free. Join the movement.

Create Content

Reentrant Locks - Part II

We may use a binary semaphore to implement a lock for mutual exclusion as in the following code snippet:

import java.util.concurrent.Semaphore;
class ReentrantLockExample {
private final Semaphore lock = new Semaphore(1);
public void foo() throws InterruptedException {
lock.acquire();
try {
// ...
bar();
} finally {
lock.release();
}
}
public void bar() throws InterruptedException {
lock.acquire();
try {
// ...
} finally {
lock.release();
}
}
}
public class Main {
public static void main(String args[]) throws Exception {
new ReentrantLockExample().foo();
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content