简体   繁体   English

使用线程处理多个tryLock()调用

[英]Handle multiple tryLock() calls with a thread

As a method of synchronizaton between threads, in Java we can use the ReentrantLock class. 作为线程之间同步的一种方法,在Java中,我们可以使用ReentrantLock类。 It has a method called tryLock() which allows the thread not to wait if it notices that a thread has not been acquired yet. 它具有一个名为tryLock()的方法,该方法允许线程在注意到尚未获取线程时不等待。 As it returns a boolean value, it can be combined with if statements to make threads do other things if they could not acquire the lock, similar to this: 当它返回一个布尔值时,可以将它与if语句结合使用if以使线程在无法获取锁的情况下执行其他操作,类似于:

if (lock.tryLock()) {
    // Do things inside the lock
    lock.unlock();
} else {
    // The lock was occupied, do other things
}

Things are great until there. 一切都很好,直到那里。 However, let's suppose that we have two (or more) locks, and we want to get both of them before entering the critical section. 但是,假设我们有两个(或更多)锁,并且我们希望在进入关键部分之前先获得两个锁。 In some specific situation, the first lock is available, but not the second one. 在某些特定情况下,第一个锁可用,但第二个锁不可用。 In order for this scenario to work correctly, I have come up with some options to choose from. 为了使此方案正常工作,我想出了一些选项供您选择。 Please note that I am more worried about the unlocking of the locks, rather than their locking: 请注意,我更担心锁的解锁,而不是锁:

// Option 1
if (lock1.tryLock() && lock2.tryLock()) {
    // Congratulations! You are inside both locks
} else {
    // How to know if you got a lock, and if so, which one?
    // You will need to "blindly" unlock both
    try {
        lock1.unlock();
        lock2.unlock();
    } catch (IllegalStateMonitorException e) {
        // Thrown when you unlock a lock which is not yours
    }
}

In my implementation, the first option basically ignored an exception, which could cause problems at some point in the execution. 在我的实现中,第一个选项基本上忽略了一个异常,该异常可能在执行过程中的某个时刻引起问题。

// Option 2
if (lock1.tryLock()) {
    if (lock2.tryLock()) {
        // Congratulations! You are inside both locks
        // Do things
        lock2.unlock();
    }
    lock1.unlock();
}

This second option takes advantage of the fact that maybe the second lock was not obtained but the first one was got. 第二种选择利用了以下事实:也许没有获得第二把锁,但得到了第一个。 I find this more efficient and intuitive. 我发现这更加有效和直观。

Which option do you think is the best one? 您认为哪种选择最好? Do you have a better implementation regarding this topic? 您是否对此主题有更好的实现?

Only ever use the second variant. 仅使用第二个变体。 The first one will cause problems, eg when the second lock was hold by another thread. 第一个会引起问题,例如,当第二个锁被另一个线程持有时。 It also doesn't unlock locks in the correct (reverse) order. 它还不会以正确的(反向)顺序解锁锁。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM