mutexsync.java

来自「Jodd是一个开源的公用Java基础类库」· Java 代码 · 共 79 行

JAVA
79
字号
package jodd.util;

/**
 * The very same Mutex, with lockTry() method added. This method locks a
 * mutex if mutex is currently unlocked and returns true. If mutex was
 * previously locked, it will not wait for its releasing: instead, it will
 * just return false.
 *
 * Since both lock() and lockTry() methods are synchronized, lockTry() can
 * not returns the faked 'true' which indicates that mutex was availiable and
 * locked, while this is not true and while another thread has meanwhile
 * locked the mutex. But, the opposite situation can happend: lockTry() may
 * return faked 'false' which indicated that mutex is in use, while meanwhile
 * another thread that has a lock may release it. However, this situations
 * occurs very, very rare and, on the other hand, this situation is not
 * harmful for the application.
 */
public class MutexSync {
	
	private volatile Thread x;
	private volatile Thread y;
	private volatile Thread current_owner;

	/**
	 * Constructor.
	 */
	public MutexSync() {
		this.y = null;
		this.x = null;
		this.current_owner = null;
	}

	public synchronized 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;
		}
	}

	/**
	 * If Mutex is locked, returns false.
	 * If Mutex is unlocked, it locks it and returns true.
	 *
	 * @return true if mutex has been locked, false otherwise.
	 */
	public synchronized boolean lockTry() {
		if (isLocked() == true) {
			return false;
		}
		lock();
		return true;
	}

	public void unlock() {
		Thread _current = Thread.currentThread();
		this.current_owner = null;
		this.y = null;								// release mutex
	}

	public boolean isLocked() {
		return (null != this.y);
	}

}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?