| net.sf.ehcache.constructs.concurrent.Sync
All known Subclasses: net.sf.ehcache.constructs.concurrent.Mutex,
Sync | public interface Sync (Code) | | version: $Id: Sync.java 519 2007-07-27 07:11:45Z gregluck $ author: Doug Lea author: Main interface for locks, gates, and conditions. author: author: Sync objects isolate waiting and notification for particular author: logical states, resource availability, events, and the like that are author: shared across multiple threads. Use of Syncs sometimes author: (but by no means always) adds flexibility and efficiency author: compared to the use of plain java monitor methods author: and locking, and are sometimes (but by no means always) author: simpler to program with. author: author: author: Most Syncs are intended to be used primarily (although author: not exclusively) in before/after constructions such as: author: author: class X { author: Sync gate; author: // ... author: author: public void m() { author: try { author: gate.acquire(); // block until condition holds author: try { author: // ... method body author: } author: finally { author: gate.release() author: } author: } author: catch (InterruptedException ex) { author: // ... evasive action author: } author: } author: author: public void m2(Sync cond) { // use supplied condition author: try { author: if (cond.attempt(10)) { // try the condition for 10 ms author: try { author: // ... method body author: } author: finally { author: cond.release() author: } author: } author: } author: catch (InterruptedException ex) { author: // ... evasive action author: } author: } author: } author:
author: Syncs may be used in somewhat tedious but more flexible replacements author: for built-in Java synchronized blocks. For example: author: author: class HandSynched { author: private double state_ = 0.0; author: private final Sync lock; // use lock type supplied in constructor author: public HandSynched(Sync l) { lock = l; } author: author: public void changeState(double d) { author: try { author: lock.acquire(); author: try { state_ = updateFunction(d); } author: finally { lock.release(); } author: } author: catch(InterruptedException ex) { } author: } author: author: public double getState() { author: double d = 0.0; author: try { author: lock.acquire(); author: try { d = accessFunction(state_); } author: finally { lock.release(); } author: } author: catch(InterruptedException ex){} author: return d; author: } author: private double updateFunction(double d) { ... } author: private double accessFunction(double d) { ... } author: } author:
author: If you have a lot of such methods, and they take a common author: form, you can standardize this using wrappers. Some of these author: wrappers are standardized in LockedExecutor, but you can make others. author: For example: author: author: class HandSynchedV2 { author: private double state_ = 0.0; author: private final Sync lock; // use lock type supplied in constructor author: public HandSynchedV2(Sync l) { lock = l; } author: author: protected void runSafely(Runnable r) { author: try { author: lock.acquire(); author: try { r.run(); } author: finally { lock.release(); } author: } author: catch (InterruptedException ex) { // propagate without throwing author: Thread.currentThread().interrupt(); author: } author: } author: author: public void changeState(double d) { author: runSafely(new Runnable() { author: public void run() { state_ = updateFunction(d); } author: }); author: } author: // ... author: } author:
author: author: One reason to bother with such constructions is to use deadlock- author: avoiding back-offs when dealing with locks involving multiple objects. author: For example, here is a Cell class that uses attempt to back-off author: and retry if two Cells are trying to swap values with each other author: at the same time. author: author: class Cell { author: long value; author: Sync lock = ... // some sync implementation class author: void swapValue(Cell other) { author: for (;;) { author: try { author: lock.acquire(); author: try { author: if (other.lock.attempt(100)) { author: try { author: long t = value; author: value = other.value; author: other.value = t; author: return; author: } author: finally { other.lock.release(); } author: } author: } author: finally { lock.release(); } author: } author: catch (InterruptedException ex) { return; } author: } author: } author: } author:
author: author: Here is an even fancier version, that uses lock re-ordering author: upon conflict: author: author: class Cell { author: long value; author: Sync lock = ...; author: private static boolean trySwap(Cell a, Cell b) { author: a.lock.acquire(); author: try { author: if (!b.lock.attempt(0)) author: return false; author: try { author: long t = a.value; author: a.value = b.value; author: b.value = t; author: return true; author: } author: finally { other.lock.release(); } author: } author: finally { lock.release(); } author: return false; author: } author: author: void swapValue(Cell other) { author: try { author: while (!trySwap(this, other) && author: !tryswap(other, this)) author: Thread.sleep(1); author: } author: catch (InterruptedException ex) { return; } author: } author: } author:
author: author: Interruptions are in general handled as early as possible. author: Normally, InterruptionExceptions are thrown author: in acquire and attempt(msec) if interruption author: is detected upon entry to the method, as well as in any author: later context surrounding waits. author: However, interruption status is ignored in release(); author: author: Timed versions of attempt report failure via return value. author: If so desired, you can transform such constructions to use exception author: throws via author: author: if (!c.attempt(timeval)) throw new TimeoutException(timeval); author:
author: author: The TimoutSync wrapper class can be used to automate such usages. author: author: All time values are expressed in milliseconds as longs, which have a maximum author: value of Long.MAX_VALUE, or almost 300,000 centuries. It is not author: known whether JVMs actually deal correctly with such extreme values. author: For convenience, some useful time values are defined as static constants. author: author: All implementations of the three Sync methods guarantee to author: somehow employ Java synchronized methods or blocks, author: and so entail the memory operations described in JLS author: chapter 17 which ensure that variables are loaded and flushed author: within before/after constructions. author: author: Syncs may also be used in spinlock constructions. Although author: it is normally best to just use acquire(), various forms author: of busy waits can be implemented. For a simple example author: (but one that would probably never be preferable to using acquire()): author: author: class X { author: Sync lock = ... author: void spinUntilAcquired() throws InterruptedException { author: // Two phase. author: // First spin without pausing. author: int purespins = 10; author: for (int i = 0; i < purespins; ++i) { author: if (lock.attempt(0)) author: return true; author: } author: // Second phase - use timed waits author: long waitTime = 1; // 1 millisecond author: for (;;) { author: if (lock.attempt(waitTime)) author: return true; author: else author: waitTime = waitTime * 3 / 2 + 1; // increase 50% author: } author: } author: } author:
author: author: In addition pure synchronization control, Syncs author: may be useful in any context requiring before/after methods. author: For example, you can use an ObservableSync author: (perhaps as part of a LayeredSync) in order to obtain callbacks author: before and after each method invocation for a given class. author: author: author: [ Introduction to this package. ] |
Method Summary | |
void | acquire() Wait (possibly forever) until successful passage.
Fail only upon interuption. | boolean | attempt(long msecs) Wait at most msecs to pass; report whether passed.
The method has best-effort semantics:
The msecs bound cannot
be guaranteed to be a precise upper bound on wait time in Java.
Implementations generally can only attempt to return as soon as possible
after the specified bound. | void | release() Potentially enable others to pass.
Because release does not raise exceptions,
it can be used in `finally' clauses without requiring extra
embedded try/catch blocks. |
ONE_CENTURY | long ONE_CENTURY(Code) | | One century in milliseconds; convenient as a time-out value
|
ONE_DAY | long ONE_DAY(Code) | | One day, in milliseconds; convenient as a time-out value *
|
ONE_HOUR | long ONE_HOUR(Code) | | One hour, in milliseconds; convenient as a time-out value *
|
ONE_MINUTE | long ONE_MINUTE(Code) | | One minute, in milliseconds; convenient as a time-out value *
|
ONE_SECOND | long ONE_SECOND(Code) | | One second, in milliseconds; convenient as a time-out value *
|
ONE_WEEK | long ONE_WEEK(Code) | | One week, in milliseconds; convenient as a time-out value *
|
ONE_YEAR | long ONE_YEAR(Code) | | One year in milliseconds; convenient as a time-out value
Not that it matters, but there is some variation across
standard sources about value at msec precision.
The value used is the same as in java.util.GregorianCalendar
|
acquire | void acquire() throws InterruptedException(Code) | | Wait (possibly forever) until successful passage.
Fail only upon interuption. Interruptions always result in
`clean' failures. On failure, you can be sure that it has not
been acquired, and that no
corresponding release should be performed. Conversely,
a normal return guarantees that the acquire was successful.
|
attempt | boolean attempt(long msecs) throws InterruptedException(Code) | | Wait at most msecs to pass; report whether passed.
The method has best-effort semantics:
The msecs bound cannot
be guaranteed to be a precise upper bound on wait time in Java.
Implementations generally can only attempt to return as soon as possible
after the specified bound. Also, timers in Java do not stop during garbage
collection, so timeouts can occur just because a GC intervened.
So, msecs arguments should be used in
a coarse-grained manner. Further,
implementations cannot always guarantee that this method
will return at all without blocking indefinitely when used in
unintended ways. For example, deadlocks may be encountered
when called in an unintended context.
Parameters: msecs - the number of milleseconds to wait.An argument less than or equal to zero means not to wait at all.However, this may still requireaccess to a synchronization lock, which can impose unboundeddelay if there is a lot of contention among threads. true if acquired |
release | void release()(Code) | | Potentially enable others to pass.
Because release does not raise exceptions,
it can be used in `finally' clauses without requiring extra
embedded try/catch blocks. But keep in mind that
as with any java method, implementations may
still throw unchecked exceptions such as Error or NullPointerException
when faced with uncontinuable errors. However, these should normally
only be caught by higher-level error handlers.
|
|
|