/ / Que se passe-t-il si je fais ça? (Verrouillage) - java, sécurité du filetage, reentrantlock

Qu'est-ce qui se passe si je fais ça? (Verrouillage) - java, sécurité du filetage, 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();
}

Si je lance le code ci-dessus, vais-je perdre mon verrou? (Le code est incomplet.)

peerLock est un ReentrantLock

Le reste peut être déduit du contexte.

Réponses:

1 pour la réponse № 1

Selon les docs, je pense que vous ne perdrez pas le verrou. Il utilise également un "nombre de mises en attente" qui est incrémenté si le même thread tente à nouveau d’obtenir un verrou.

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

De même, pour unlock (), le nombre de mises en attente est décrémenté et s’il est égal à zéro, le verrou est libéré.

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

Il est donc assez clair dans la documentation que le thread appelant hasPeer () depuis handleLinkWeights () ne perdra pas son verrou.