java - Access the submitted object from within a ThreadPoolExecutor -
public void execute(runnable command)
this command object contains submitted object, seems have been wrapped.
how can access submitted object within custom thread pool executor? or not such idea try , access submitted object inside threadpoolexecutor's before/after/execute methods?
don't use execute
, use submit
, returns future
, handle task. here's example code:
executorservice service = executors.newcachedthreadpool(); callable<string> task = new callable<string>() { public string call() throws exception { return "hello world"; } }; future<string> future = service.submit(task);
although can't access task directly, can still interact it:
future.cancel(); // won't start task if not started string result = future.get(); // blocks until thread has finished calling task.call() , returns result future.isdone(); // true if complete
you can interact service:
service.shutdown(); //etc
edited incorporate comments:
if want logging, use anonymous class override afterexecute()
method, this:
threadpoolexecutor executor = new threadpoolexecutor(1, 1, 1, timeunit.seconds, new arrayblockingqueue<runnable>(1)) { @override protected void afterexecute(runnable r, throwable t) { // logging here super.afterexecute(r, t); } };
override other methods required.
quick plug: imho, bible subject java concurrency in practice - recommend buy , read it.
Comments
Post a Comment