/ / Co się stanie, jeśli to zrobię? (Blokowanie) - Java, bezpieczeństwo wątków, blokada ponownego wysyłania

Co się stanie, jeśli to zrobię? (Blokowanie) - 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();
}

Jeśli uruchomię powyższy kod, czy utracę blokadę? (Kod jest niekompletny).

peerLock jest ReentrantLock

Resztę można wywnioskować z kontekstu.

Odpowiedzi:

1 dla odpowiedzi № 1

Według dokumentów, myślę, że nie stracisz blokady. Wykorzystuje również „blokadę”, która jest zwiększana, jeśli ten sam wątek próbuje ponownie uzyskać blokadę.

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

Podobnie w przypadku odblokowania () liczba wstrzymań jest zmniejszana, a jeśli wynosi zero, blokada jest zwalniana.

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

Jest to całkiem jasne z dokumentacji, wywołanie wątku hasPeer () z handleLinkWeights () nie straci blokady.