java - Using Map of Futures, how do I notify() a single element within? -
i'm attempting hold static list of futures, , @ later time either cancel() or notify() futures in progress. callable class associated these futures has wait() within it, each 1 must notified outside source continue. however, calls notify() appear ignored, callables never past wait statement. class list of futures looks this:
private static map <string, future<object>> results = new hashmap <string, future<object>>(); executorservice taskexecutor; public void dostuff() { taskexecutor = executors.newcachedthreadpool(); // loop inifinitely - external processes modify conditions within while(!shutitdown) { if (<condition1>) { // condition 1 dictates kick-off of new callable future<object> future = taskexecutor.submit(new mycallable(id)); results.put(id, future); } else if (<condition2>) { // condition 2 represents callable in wait status needs // notified future<object> future = results.get(uid); if (future != null) { synchronized(future) { future.notify(); // doesn't have desired effect! } } } } } the callable class mockup now, looks similar this:
public class mycallable implements callable<object> { private string id; public mycallable(string id) { this.id = id; } @override public object call() throws exception { try { // work here, wait on outside notification synchronized(this) { this.wait(); // never gets past here!!! } // other work here, once has been notified } catch (interruptedexception e) { e.printstacktrace(); } return null; } the notify() method called, seems have no effect. object reference future appears valid (i.e. local variable "future" matches reference of future stored in static list).
i'm missing basic concept of concurrency here, expected when condition2 met, callable proceed past wait() call.
note if use cancel() instead of notify(), interrupts runnable , causes interruptedexception expect.
you need notify exact same object. in case notifying on future object waiting on mycallable object. unfortunately, don't know of easy way mycallable object see wrapped future there no wait wait() on it.
one solution pass in lock object mycallable constructor , save along associated future. like:
private static map <string, futurelock> results = new hashmap <string, futurelock>(); ... object lock = new object(); future<object> future = taskexecutor.submit(new mycallable(id, lock)); results.put(id, new futurelock(future, lock)); ... public class futurelock { private future<object> future; private object lock; public futurelock(future<object> future, object lock) { this.future = future; this.lock = lock; } public void notify() { synchronized (lock) { lock.notify(); } } public object get() throws exception { return future.get(); } } public class mycallable { private object lock; public mycallable(string id, object lock) { this.lock = lock; ... } }
Comments
Post a Comment