📄 mutex.java
字号:
package jodd.util;
/**
* Class that provides fast mutual exclusion using Leslie Lamport's "Fast
* Mutal Exclusion" algorithm.
*
* This class does not use the built-in synchronization monitor primitives of
* the Java language, thus allowing for proper synchronization across method
* calls.
*
* Object (i.e. resource) that uses Mutex must be accessed only between
* lock() and unlock().
*/
public class Mutex {
/* volatile modifier are used in order to inform the compiler not to do
clever caching tricks and assumptions regarding their contents. */
private volatile Thread x;
private volatile Thread y;
private volatile Thread current_owner;
/**
* Constructor.
*/
public Mutex() {
this.y = null;
this.x = null;
this.current_owner = null;
}
/**
* Aquire mutex. When this method returns, the calling thread have the mutex,
* and is can for all practical purposes be said to be within whatever
* critical region this mutex instance is supposed to protect.
*
* The method uses the calling thread's thread reference (obtained via
* Thread.currentThread()) to uniquely identify a thread.
*/
public void lock() {
Thread _current = Thread.currentThread();
while (true) {
this.x = _current;
if (this.y != null) {
_current.yield();
continue;
}
this.y = _current;
if (this.x != _current) {
_current.yield();
if (this.y != _current) {
_current.yield();
continue;
}
}
this.current_owner = _current;
break;
}
}
/**
* Release an aquired mutex. This particular implementation will allow both
* releases from non-owning threads, as well as multiple releases.
*/
public void unlock() {
Thread _current = Thread.currentThread();
this.current_owner = null;
this.y = null; // release mutex
}
/**
* Probe the mutex state. Note that this is inaccurate, and can only serve as
* an indication of whether the mutex is in use or not.
*
* @return true if the mutex is locked at the time of the probe,
* false otherwise.
*/
public boolean isLocked() {
return (null != this.y);
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -