如果我这样做会怎么样? (锁定)

时间:2014-02-21 00:00:35

标签: java thread-safety reentrantlock

public void handleLinkWeights(LinkWeightMessage m) { //Calculate shortest paths when all edges and peers discovered.
    peerLock.lock();
    int size = m.weights.length; //All lists should be the same size

    for (int x = 0; x < size; ++x){
        NodeMessage a = m.anodes.get(x),
                    b = m.bnodes.get(x);

        if (hasPeer(a.address, a.port)) {
            // ...
        }
    }

    peerLock.unlock();
    //TODO
}

private boolean hasPeer(String address, int port) {
    peerLock.lock();

    peerLock.unlock();
}

如果我运行上面的代码,我会丢失锁吗? (代码不完整。)

peerLockReentrantLock

其余的可以从上下文中推断出来。

1 个答案:

答案 0 :(得分:1)

根据文件,我认为你不会失去锁定。它还使用“保持计数”,如果同一个线程再次尝试获取锁定,它将递增。

public void lock()

Acquires the lock.

Acquires the lock if it is not held by another thread and returns immediately, setting the lock hold count to one.

If the current thread already holds the lock then the hold count is incremented by one and the method returns immediately.

If the lock is held by another thread then the current thread becomes disabled for thread scheduling purposes and lies dormant until the lock has been acquired, at which time the lock hold count is set to one.

Specified by:
    lock in interface Lock 

类似地,对于unlock(),保持计数递减,如果为零,则释放锁定。

public void unlock()

Attempts to release this lock.

If the current thread is the holder of this lock then the hold count is decremented. If the hold count is now zero then the lock is released. If the current thread is not the holder of this lock then IllegalMonitorStateException is thrown.

Specified by:
    unlock in interface Lock
Throws:
    IllegalMonitorStateException - if the current thread does not hold this lock

从文档中可以清楚地看出,来自handleLinkWeights()的调用hasPeer()的线程不会失去锁定。