Exception capture
In the previous use of executor, in order to record the task thread's exception exit will use Threadfactory to set the thread's Uncaughtexceptionhandler, but according to the verification found in the book, When performing a task with Executorservice.submit, the exception thrown by the thread is not captured by the processor and is captured when the task is submitted using Executor.execute. The code is as follows:
FinalUncaughtexceptionhandler handler =NewUncaughtexceptionhandler () {@Override Public voidUncaughtexception (FinalThread T,Finalthrowable e) {System.out.println ("Uncaught exception"); } }; Threadfactory exfactory=Newthreadfactory () {@Override PublicThread Newthread (FinalRunnable R) {Thread x=NewThread (R); X.setuncaughtexceptionhandler (handler); returnx; } }; Executorservice es=Executors.newsinglethreadexecutor (exfactory);
Es.execute (New Runnable () {Es.submit (NewRunnable () {@Override Public voidrun () {ArrayList<Integer> x =NewArraylist<integer>(); System.out.println (X.get (10)); Index out of Bound}});
If the exception to get the submit task needs to use the future object it returns, the actuator get method is as follows:
Executorservice es =Executors.newsinglethreadexecutor (exfactory); Future<Void> f = (future<void>) es.submit (NewRunnable () {@Override Public voidrun () {ArrayList<Integer> x =NewArraylist<integer>(); System.out.println (X.get (10)); } }); Try{f.get (); } Catch(interruptedexception E1) {//TODO auto-generated Catch blockE1.printstacktrace (); } Catch(executionexception E1) {//TODO auto-generated Catch blockE1.printstacktrace (); }
At this point the program prints an error message.
Java Concurrency: Executor