If I want to ensure exclusive access to an object in Java, I can write something like this:
...
Zoo zoo = findZoo();
synchronized(zoo)
{
zoo.feedAllTheAnimals();
...
}
Is there a way to check if an object is currently locked? I don't want my thread to wait if another thread is accessing zoo
. If zoo
is not locked, I want my thread to acquire the lock and execute the synchronized
block; if not, I want it to skip it.
How can I do this?
Typically, threads cannot acquire locks twice in a row: a thread must release an acquired lock before attempting to acquire it again. However, reentrant locks can be acquired multiple times by the same thread.
The lock() method is one of the most important methods of the Lock interface. It is used for acquiring the lock. For thread scheduling purposes, the current thread becomes disabled when the lock is not available. The lock() method is a public method that returns void.
Java Thread holdLock() methodThe holdLock() method of thread class returns true if the current thread holds the monitor lock on the specified object.
A ReentrantLock is owned by the thread last successfully locking, but not yet unlocking it. A thread invoking lock will return, successfully acquiring the lock, when the lock is not owned by another thread. The method will return immediately if the current thread already owns the lock.
You can't do it using the low-level native synchronization embedded in Java. But you can do it using the high-level APIs provided in the concurrent package.
Lock lock = new ReentrantLock();
....
//some days later
....
boolean isLocked = lock.tryLock();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With