Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get locked/unlocked status of java.util.concurrent.locks.Lock

Is there a way to get something like isLocked status of a Lock?

What I am doing is acquiring a lock before a loop operation and releasing it only after a certain condition is met AND the lock is already locked. So I need it ask the lock if it is already locked and I can't seem to find a way in the API to do it.

like image 760
amphibient Avatar asked Sep 17 '25 13:09

amphibient


2 Answers

You can use tryLock() to get the Lock if it's free.

Lock is an interface, so as long as all you need is any implementation of a Lock, then ReentrantLock has an isLocked() method; however, I am not certain why you would only want it if it is currently locked.

Make sure that this is not a case of the XY-Problem. Or are you just saying that you wouldn't need to unlock it if it were already unlocked?

like image 162
Steve P. Avatar answered Sep 19 '25 04:09

Steve P.


if (lock.tryLock())
{
    // Got the lock
    try
    {
        // Process record
    }
    finally
    {
        // Make sure to unlock so that we don't cause a deadlock
        lock.unlock();
    }
}
else
{
    // Someone else had the lock, abort
}

see this

like image 23
Abdullah Shoaib Avatar answered Sep 19 '25 03:09

Abdullah Shoaib