synchronize
?
synchronize
.
Lock
Interfacew
msec between tries.
interface Lock void lock() throws InterruptedException void unlock() boolean tryLock(int retries, long wait) throws InterruptedException
class Mutex implements Lock private boolean locked public Mutex(boolean locked) this.locked = locked
public synchronized void unlock() locked = false notify()
notify()
is unfair; use notifyAll()
for fairness.
notifyAll()
's expensive.
public void lock() throws InterruptedException if (Thread.interrupted()) throw new InterruptedException() synchronized (this) try while (locked) wait(); locked = true catch (InterruptedException ie) notify() throw ie
notify()
.
public boolean tryLock(int retries, long delay) throws InterruptedException if (Thread.interrupted()) throw new InterruptedException() boolean got_lock synchronized (this) if (!locked) locked = true return true if ((delay < 1) || (retries < 1)) return false do got_lock = retry(delay) while (!got_lock && --retries > 0) return got_lock
private boolean retry(long delay) try long startTime = System.currentTimeMillis() long delayTime = msecs while true wait(delayTime) if !locked locked = true return true else long now = System.currentTimeMillis() delayTime = msecs - (now - startTime) if (delayTime <= 0) return false catch InterruptedException ie notify() throw ie
wait(long)
object method.
synchronize (lock) { /* whatever */ } try mutex.lock() try // whatever finally mutex.unlock() catch (InterruptedException ie) // cancellation behavior.
class Unsynchronized private String [] records void op() // whatever
wrap them in synchronized methods.
class Synchronized extends Unsynchronized private mutex mtx void op() try try mtx.lock() super.op() finally mtx.unlock() catch InterruptedExecution Thread.currentThread().interrupt()
abstract class MutexTemplate private Mutex mutex = new Mutex(false) void execute(Object o) try mutex.lock() function(o) catch (InterruptedException ie) interrupt(ie) finally { mutex.unlock() } abstract protected void function(Object o) abstract protected void interrupt(InterruptedException ie)
function()
does the work.
interrupt()
does the clean-up.
function()
and interrupt()
in a
concrete subclass of the template class.
class counter extends MutexTemplate private int count = 0 public void addTo(int i) function(new Integer(i)) protected void function(Object o) count += ((Integer) o).intValue() protected void interrupt(InterruptedException ie) { }
interface RWLock Lock readLock() Lock writeLock()
class Writer implements Runnable private RWLock rwLock Writer(RWLock rwl) rwLock = rwl void run() rwLock.writeLock.lock() // whatever rwLock.writeLock.unlock()
This page last modified on 17 July 2003.