synchronize?
synchronize.
Lock Interface.w 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()
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;
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 MutexMethodAdapter
private final Mutex mutex
MutexMethodAdapter(Mutex m) { mutex = m; }
public void execute(Runnable r)
throws InterruptedException
mutex.lock();
try { r.run(); }
finally { mutex.unlock(); }
class counter
private final MutexMethodAdapter
lock = new MutexMethodAdapter(new Mutex(false))
private long count = 0
private class adder implements Runnable
private int v
adder(int v) { this.v = v }
public void run() { count += v }
public void addTo(int v)
try { lock.execute(new adder(v)) }
catch (Exception e) { }
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)
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) { }
This page last modified on 1 August 2002.