[concurrency-interest] Periodic/MutableFuture
Jacob Hookom
jacob at hookom.net
Mon Jan 4 23:11:26 EST 2010
In using Java's ScheduledExecutorService, I was looking for a way to
match a common usecase in applications whereby I have some variable
which needs periodic/async updating. The common case is scheduling
periodic updates from the database into memory with non-blocking reads.
It'd be nice if we had versions which took in Callable<V> to
scheduleAt/With...(...) and returned a ScheduledFuture<V> by which
successive calls to get() returned the current of the last execution of
the Callable<V> given some interval.
Example:
public <V> ScheduledFuture<V> scheduleAtFixedRate(Callable<V> callable,
long initialDelay, long period, TimeUnit unit);
(rough code of desired behavior on existing API):
public class PeriodicFuture<V> extends FutureTask<V> {
private volatile V value;
private final Callable<V> callable;
public PeriodicFuture(Callable<V> callable) {
super(callable);
this.callable = callable;
}
public V get() throws InterruptedException, ExecutionException {
if (!this.isDone()) {
this.value = super.get();
}
return this.value;
}
public V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
if (!this.isDone()) {
this.value = super.get(timeout, unit);
}
return this.value;
}
public void run() {
if (!this.isDone()) {
super.run();
}
try {
this.value = this.callable.call();
} catch (Exception e) {
this.setException(e);
}
}
}
More information about the Concurrency-interest
mailing list