Java Concurrency: Executor

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.