質問

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();
}

If I run the above code, will I lose my lock? (The code is incomplete.)

peerLock is a ReentrantLock

The rest can be inferred from context.

役に立ちましたか?

解決

According to the docs, I think you will not lose the lock. It also utilizes a "hold count" which gets incremented if the same thread tries to acquire lock again.

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 

Similarly, for unlock() the hold count is decremented and if it's zero, the lock is released.

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

So it is pretty clear from the docs, the thread calling hasPeer() from handleLinkWeights() will not lose its lock.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top