KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jgroups > util > ReentrantLatch


1 package org.jgroups.util;
2
3 /**
4  * Enables safely locking and unlocking a shared resource, without blocking the calling threads. Blocking is only done
5  * on the 'passThrough' method.
6  *
7  * @author yaronr / Dmitry Gershkovich
8  * @version 1.0
9  */

10 public final class ReentrantLatch {
11
12     boolean locked;
13
14     /**
15      * Create a new unlocked latch.
16      */

17     public ReentrantLatch() {
18         this(false);
19     }
20
21     /**
22      * Create a reentrant latch
23      *
24      * @param locked is the latch to be created locked or not
25      */

26     public ReentrantLatch(boolean locked) {
27         this.locked = locked;
28     }
29
30     /**
31      * Lock the latch. If it is already locked, this method will have no side effects. This method will not block.
32      */

33     public synchronized void lock() {
34         if (!locked) {
35             locked = true;
36         }
37     }
38
39     /**
40      * Unlock the latch. If it is already unlocked, this method will have no side effects. This method will not block.
41      */

42     public synchronized void unlock() {
43         if (locked) {
44             locked = false;
45             notifyAll();
46         }
47     }
48
49     /**
50      * Pass through only when the latch becomes unlocked. If the latch is locked, wait until someone unlocks it. Does
51      * not lock the latch.
52      *
53      * @throws InterruptedException
54      */

55     public synchronized void passThrough() throws InterruptedException JavaDoc {
56         while (locked) {
57             wait();
58         }
59     }
60 }
Popular Tags