public class SynchronizedVariable extends Object implements Executor
final. This
helps avoid the need to synchronize just to obtain the reference
to the synchronized variable itself.
static variables. It almost
always works out better to rely on synchronization internal
to these objects, rather than class locks.
set method that sets to a new value and returns
previous value. For example, for a SynchronizedBoolean b,
boolean old = b.set(true) performs a test-and-set.
commit method that sets to new value only
if currently holding a given value.
For example, here is a class that uses an optimistic update
loop to recompute a count variable represented as a
SynchronizedInt.
class X {
private final SynchronizedInt count = new SynchronizedInt(0);
static final int MAX_RETRIES = 1000;
public boolean recomputeCount() throws InterruptedException {
for (int i = 0; i < MAX_RETRIES; ++i) {
int current = count.get();
int next = compute(current);
if (count.commit(current, next))
return true;
else if (Thread.interrupted())
throw new InterruptedException();
}
return false;
}
int compute(int l) { ... some kind of computation ... }
}
swap method that atomically swaps with another
object of the same class using a deadlock-avoidance strategy.
Waitable subclasses provide notifications on
every value update, and support guarded methods of the form
whenpredicate, that wait until the
predicate hold, then optionally run any Runnable action
within the lock, and then return. All types support:
execute
method that runs the runnable within the lock.
All classes except SynchronizedRef and WaitableRef implement
Cloneable and Comparable.
Implementations of the corresponding
methods either use default mechanics, or use methods that closely
correspond to their java.lang analogs. SynchronizedRef does not
implement any of these standard interfaces because there are
many cases where it would not make sense. However, you can
easily make simple subclasses that add the appropriate declarations.
[ Introduction to this package. ]| 构造器和说明 |
|---|
SynchronizedVariable()
Create a SynchronizedVariable using itself as the lock
|
SynchronizedVariable(Object lock)
Create a SynchronizedVariable using the supplied lock
|
| 限定符和类型 | 方法和说明 |
|---|---|
void |
execute(Runnable command)
If current thread is not interrupted, execute the given command
within this object's lock
|
Object |
getLock()
Return the lock used for all synchronization for this object
|
protected final Object lock_
public SynchronizedVariable(Object lock)
public SynchronizedVariable()
public Object getLock()
public void execute(Runnable command) throws InterruptedException
execute 在接口中 ExecutorInterruptedExceptionCopyright © 2024. All rights reserved.