java - how Futures.addCallback guarantee the callback to be executed at the thread executing the future task? -
code shown below:
final listeningexecutorservice executor = moreexecutors.listeningdecorator(executors.newfixedthreadpool(4)); final callable<string> asynctask = new callable<string>() { @override public string call() throws exception { return testfuture.computeresult(); } }; final int listsize = 10; final list<listenablefuture<string>> listenablefutures = lists.newarraylistwithexpectedsize(listsize); (int = 0; < listsize; i++) { listenablefutures.add(executor.submit(asynctask)); } (final listenablefuture<string> listenablefuture2 : listenablefutures) { futures.addcallback(listenablefuture2, new futurecallback<string>() { @override public void onsuccess(final string result) { system.out.println("callback success " + result + " @ " + thread.currentthread().getname()); } @override public void onfailure(final throwable thrown) { system.out.println("callback failed " + thrown.getmessage()); } }); }
i cannot figure out how callback scheduled executed @ thread executing asynctask
?
i can see futures.addcallback
calls addcallback(future, callback, moreexecutors.samethreadexecutor());
, donnot know how moreexecutors.samethreadexecutor guarantee this?
samethreadexecutor()
executes runnable
that's passed execute(runnable)
method inline: is, calls run()
on it. nothing related threads @ all. , callback runnable
s passed associated executor
on same thread executes asynctask
because listeningexecutorservice
wraps asynctask
in futuretask
calls callbacks when done()
method called.
note: not guaranteed of callbacks executed on thread executes asynctask
. example, if add callback after asynctask
has completed, it'll executed on thread added callback on (assuming don't provide executor
other samethreadexecutor()
callback use).
Comments
Post a Comment