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

2019-02-16 15:13发布

This question already has an answer here:

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?

3条回答
唯我独甜
2楼-- · 2019-02-16 15:26

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

查看更多
家丑人穷心不美
3楼-- · 2019-02-16 15:30

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();
查看更多
霸刀☆藐视天下
4楼-- · 2019-02-16 15:41

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.

查看更多
登录 后发表回答