Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: How to check if a lock can be acquired? [duplicate]

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?

like image 726
Tony the Pony Avatar asked May 26 '11 09:05

Tony the Pony


People also ask

Can two threads acquire the same lock?

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.

What does lock lock (); do in Java?

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.

How do you check if a thread holds a lock in Java?

Java Thread holdLock() methodThe holdLock() method of thread class returns true if the current thread holds the monitor lock on the specified object.

Are locks in Java reentrant?

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.


1 Answers

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();
like image 117
Suraj Chandran Avatar answered Oct 27 '22 14:10

Suraj Chandran