Is there a Mutex in Java?
Any object in Java can be used as a lock using a synchronized
block. This will also automatically take care of releasing the lock when an exception occurs.
Object someObject = ...;synchronized (someObject) { ...}
You can read more about this here: Intrinsic Locks and Synchronization
See this page: http://www.oracle.com/technetwork/articles/javase/index-140767.html
It has a slightly different pattern which is (I think) what you are looking for:
try { mutex.acquire(); try { // do something } finally { mutex.release(); }} catch(InterruptedException ie) { // ...}
In this usage, you're only calling release()
after a successful acquire()
import java.util.concurrent.locks.Lock;import java.util.concurrent.locks.ReentrantLock;private final Lock _mutex = new ReentrantLock(true);_mutex.lock();// your protected code here_mutex.unlock();