KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > jodd > util > Mutex


1 // Copyright (c) 2003-2007, Jodd Team (jodd.sf.net). All Rights Reserved.
2

3 package jodd.util;
4
5 /**
6  * Provides simple mutual exclusion.
7  * <p>
8  * Interesting, the previous implementation based on Leslie Lamport's
9  * "Fast Mutal Exclusion" algorithm was not working, proabably due wrong
10  * implementation.
11  * <p>
12  * Object (i.e. resource) that uses Mutex must be accessed only between
13  * {@link #lock()} and {@link #unlock()}.
14  */

15 public class Mutex {
16
17     private Thread JavaDoc owner = null;
18
19     /**
20      * Blocks execution and acquires a lock. If already inside of critical block,
21      * it simply returs.
22      */

23     public synchronized void lock() {
24         Thread JavaDoc currentThread = Thread.currentThread();
25         if (owner == currentThread) {
26             return;
27         }
28         while (owner != null) {
29             try {
30                 wait();
31             } catch (InterruptedException JavaDoc iex) {
32                 notify();
33             }
34         }
35         owner = currentThread;
36     }
37
38     /**
39      * Acquires a lock. If lock already acquired, returns <code>false</code>,
40      */

41     public synchronized boolean tryLock() {
42         Thread JavaDoc currentThread = Thread.currentThread();
43         if (owner == currentThread) {
44             return true;
45         }
46         if (owner != null) {
47             return false;
48         }
49         owner = currentThread;
50         return true;
51     }
52
53     /**
54      * Releases a lock.
55      */

56     public synchronized void unlock() {
57         owner = null;
58         notify();
59     }
60 }
61
Popular Tags