10

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?

Tony the Pony
  • 40,327
  • 71
  • 187
  • 281

3 Answers3

7

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();
Suraj Chandran
  • 24,433
  • 12
  • 63
  • 94
  • Wouldn't `Lock` be using `synchronized` internally since it would be hard to avoid the low level API. If this is the case, how would it `Lock` be using `synchronized` to achieve `tryLock`. – Mathew Kurian Nov 30 '13 at 01:06
  • @MathewKurian It uses `synchronized` to access internal variables, then the functionality splits. tryLock only checks and returns immediately whether it could take the lock at that point or not, lock uses the wait() mechanism to wait until the lock is unlocked. Either way, the critical section (`synchronized`) itself will only take maybe 1-2 microseconds. At most. Probably closer to a few hundred nanoseconds. – Paul Stelian Feb 02 '19 at 15:01
5

you can use Lock.tryLock(). more concretely, java.util.concurrent.locks.ReentrantLock

irreputable
  • 44,725
  • 9
  • 65
  • 93
1

You may do it manually too. Although you already have satisfying answer with ReentrantLock ;)

private boolean flag;
private final Object flagLock = new Object();
private final Object actualLock = new Object();

//...

boolean canAquireActualLock = false;
synchronized (flagLock) {
    if (!flag) {
        flag = canAquireActualLock = true;
    }
}
if (canAquireActualLock) {
    try {
        synchronized (actualLock) {

            // the code in actual lock...

        }
    } finally {
        synchronized (flagLock) { flag = false; }
    }
}

Of course you could wrap with convenient methods.

Tomasz Gawel
  • 8,379
  • 4
  • 36
  • 61