i'm working on software development framework parallel computing javaseis.org. need robust mechanism reporting thread exceptions. during development, knowing exceptions came has high value, err on side of over-reporting. able handle junit4 testing in threads well. approach below reasonable or there better way ?
import java.util.concurrent.callable; import java.util.concurrent.executorservice; import java.util.concurrent.executors; import java.util.concurrent.future; public class testthreadfailure { public static void main(string[] args) { int size = 1; executorservice exec = executors.newfixedthreadpool(size); threadfailtask worker = new threadfailtask(); future<integer> result = exec.submit(worker); try { integer value = result.get(); system.out.println("result: " + value); } catch (throwable t) { system.out.println("caught failure: " + t.tostring()); exec.shutdownnow(); system.out.println("stack trace:"); t.printstacktrace(); return; } throw new runtimeexception("did not catch failure !!"); } public static class threadfailtask implements callable<integer> { @override public integer call() { int nbuf = 65536; double[][] buf = new double[nbuf][nbuf]; return new integer((int) buf[0][0]); } } }
i don't believe there standard 'hook' these exceptions when using submit()
. however, if need support submit()
(which sounds reasonable, given use callable
), can wrap callables , runnables :
executorservice executor = new threadpoolexecutor(1, 10, 60, timeunit.seconds, new linkedblockingdeque<runnable>()) { @override public <t> future<t> submit(final callable<t> task) { callable<t> wrappedtask = new callable<t>() { @override public t call() throws exception { try { return task.call(); } catch (exception e) { system.out.println("oh boy, broke!"); e.printstacktrace(); throw e; } } }; return super.submit(wrappedtask); } };
of course, method works if you're 1 building executorservice
in first place. furthermore, remember override 3 submit()
variants.
Comments
Post a Comment