2014-02-21 4 views
-1
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(); 
} 

Если я запустил вышеуказанный код, потеряю ли я замок? (Код является неполным.)Что произойдет, если я это сделаю? (Запирание)

peerLock является ReentrantLock

Остальные могут быть выведены из контекста.

+1

Вы попробовали? Вы читали Javadoc для «ReentrantLock»? –

+0

Почему вы думаете, что потеряете свою блокировку в этом примере? –

+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 

Аналогично, для разблокировки() счетчик удержания уменьшается, а если это ноль, блокировка снимается.

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 

Так что это довольно ясно из документации, поток вызова hasPeer() из handleLinkWeights() не потеряет свою блокировку.

+0

Спасибо. Смотрел, что может произойти, и если я должен изменить структуру. –

Смежные вопросы