/ / Was passiert wenn ich das mache? (Verriegelung) - Java, Fadensicherung, Wiedereintrittssperre

Was passiert, wenn ich das mache? (Locking) - Java, Thread-Sicherheit, 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();
}

Wenn ich den obigen Code ausführte, verliere ich meine Sperre? (Der Code ist unvollständig.)

peerLock ist ein ReentrantLock

Der Rest lässt sich aus dem Kontext ableiten.

Antworten:

1 für die Antwort № 1

Laut den Unterlagen, denke ich, werden Sie das Schloss nicht verlieren. Es verwendet auch eine "Haltezählung", die erhöht wird, wenn derselbe Thread erneut versucht, die Sperre zu erlangen.

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

In ähnlicher Weise wird für "unlock ()" der Hold-Count verringert und wenn der Wert Null ist, wird die Sperre aufgehoben.

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

Aus den Dokumenten ist also ziemlich klar, dass der Thread, der hasPeer () von handleLinkWeights () aufruft, seine Sperre nicht verliert.