Skip to content

Instantly share code, notes, and snippets.

@meatcar
Last active August 29, 2015 14:17
Show Gist options
  • Save meatcar/b98e4827f1be003b969b to your computer and use it in GitHub Desktop.
Save meatcar/b98e4827f1be003b969b to your computer and use it in GitHub Desktop.
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class FutureManager {
Executor executor = Executors.newSingleThreadExecutor();
Map<String, Future> futures;
long timeToSleep;
public FutureManager(long sleep) {
this.timeToSleep = sleep;
futures = new HashMap<>();
Thread t = new Thread(new Runnable() {
@Override
public void run() {
try {
for (Map.Entry<String, Future> e : futures.entrySet()) {
if (e.getValue().isDone()) {
cleanup(e.getKey()); // cleanup
}
}
Thread.sleep(timeToSleep);
} catch (InterruptedException e) {
// ignore it and exit.
}
}
});
executor.execute(t);
}
private void cleanup(String id) {
this.futures.remove(id);
}
public void add(String id, Future f) {
futures.put(id, f);
}
public void cancel(String id) {
Future f = futures.get(id);
if (f != null) {
f.cancel(true);
}
cleanup(id);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment