Last active
August 29, 2015 14:17
-
-
Save meatcar/b98e4827f1be003b969b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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