KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > jodd > util > MutexSync


1 package jodd.util;
2
3 /**
4  * The very same Mutex, with lockTry() method added. This method locks a
5  * mutex if mutex is currently unlocked and returns true. If mutex was
6  * previously locked, it will not wait for its releasing: instead, it will
7  * just return false.
8  *
9  * Since both lock() and lockTry() methods are synchronized, lockTry() can
10  * not returns the faked 'true' which indicates that mutex was availiable and
11  * locked, while this is not true and while another thread has meanwhile
12  * locked the mutex. But, the opposite situation can happend: lockTry() may
13  * return faked 'false' which indicated that mutex is in use, while meanwhile
14  * another thread that has a lock may release it. However, this situations
15  * occurs very, very rare and, on the other hand, this situation is not
16  * harmful for the application.
17  */

18 public class MutexSync {
19     
20     private volatile Thread x;
21     private volatile Thread y;
22     private volatile Thread current_owner;
23
24     /**
25      * Constructor.
26      */

27     public MutexSync() {
28         this.y = null;
29         this.x = null;
30         this.current_owner = null;
31     }
32
33     public synchronized void lock() {
34         Thread _current = Thread.currentThread();
35         while (true) {
36             this.x = _current;
37             if (this.y != null) {
38                 _current.yield();
39                 continue;
40             }
41             this.y = _current;
42             if (this.x != _current) {
43                 _current.yield();
44                 if (this.y != _current) {
45                     _current.yield();
46                     continue;
47                 }
48             }
49             this.current_owner = _current;
50             break;
51         }
52     }
53
54     /**
55      * If Mutex is locked, returns false.
56      * If Mutex is unlocked, it locks it and returns true.
57      *
58      * @return true if mutex has been locked, false otherwise.
59      */

60     public synchronized boolean lockTry() {
61         if (isLocked() == true) {
62             return false;
63         }
64         lock();
65         return true;
66     }
67
68     public void unlock() {
69         Thread _current = Thread.currentThread();
70         this.current_owner = null;
71         this.y = null; // release mutex
72
}
73
74     public boolean isLocked() {
75         return (null != this.y);
76     }
77
78 }
79
Popular Tags