package jutil; /** * The methods in this class are meant to mimic the * indivisible swap and testAndSet instructions * provided by most computers. */ public class Lock { /** * if true, then lock is locked */ private boolean locked = false; /** * @param val initial value of lock */ public Lock(boolean val) { locked = val; } /** * sets lock to false */ public Lock() { this(false); } /** * @return state of lock */ public synchronized boolean isLocked() { return locked; } /** * sets lock to true without interruption. */ public synchronized void lock() { locked = true; } /** * Sets lock to false without interruption. */ public synchronized void unlock() { locked = false; } /** * sets lock to true without interruption * @return former value of lock */ public synchronized boolean testAndSet() { boolean temp = locked; locked = true; return temp; } /** * Swaps this locks state with the state of another * lock without interruption. * @param other some other lock */ public synchronized void swap(Lock other) { boolean temp = locked; locked = other.locked; other.locked = temp; } }