KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > SOFA > Util > Lock


1 /* $Id: Lock.java,v 1.1.1.1 2003/02/11 16:19:41 bures Exp $ */
2 package SOFA.Util;
3
4 /** Lock.
5   *
6   * @author Petr Hnetynka
7   */

8 public class Lock {
9
10   private boolean locked;
11
12   /** Constructor.
13     * @param l if should be locked or not
14     */

15   public Lock(boolean l) {
16     locked = l;
17   }
18
19   /** Lock. If lock is locked, then wait.
20     * @return false, if waiting was interrupted
21     */

22   synchronized public boolean lock() {
23     try {
24       while (locked)
25         wait(); /* wait until somenone call notify() */
26       locked = true;
27     } catch (InterruptedException JavaDoc e) {
28       return false;
29     }
30     return true;
31   }
32
33   /** Try lock.
34     * @return false, if can't get lock immediatelly
35     */

36   synchronized public boolean tryLock() {
37     if (locked)
38       return false;
39     else {
40       locked = true;
41       return true;
42     }
43   }
44   
45   /** Unlock.
46     */

47   synchronized public void unlock() {
48     locked = false;
49     notify(); /* wake up others which wait for lock */
50   }
51   
52   /** Test if lock is locked */
53   synchronized public boolean isLocked() {
54     return locked;
55   }
56 }
57
Popular Tags