Notes [Java7 Concurrent Programming Manual]4.5 runs multiple tasks and processes the first result threadpoolexecutor

Source: Internet
Author: User

Notes [Java7 Concurrent Programming manual] series catalogue

Brief introduction

When I saw the title, I was also very puzzled, because I didn't understand the meaning of the expression.
OK, concurrent programming is a common problem is: when the use of multiple concurrent tasks to solve a problem, often only need to care about the first result of the task, such as: When validating an algorithm, if a 5 algorithm execution, then the first to return the result is the fastest.

In this chapter you will learn how to use Threadpoolexecutor to achieve similar scenarios;

This chapter Threadpoolexecutor use of the experience
    1. Use Threadpoolexecutor.invokeany (list); Let the thread pool help us get the results of the fastest return. Executes the given task, and returns the result if a task has completed successfully (that is, an exception is thrown). Once normal or abnormal returns, the unfinished task is canceled. If the given collection is modified while this operation is in progress, the result of this method is indeterminate.
    2. The JDK shows that the task is identified as: no exception thrown, normal return;
    3. When you get the first result, the executor cancels the unfinished task, and in multi-threading: Throws a Interruptedexception exception when the thread is waiting, hibernating, or occupied during the activity or during the activity and the thread is interrupted
    4. If all the tasks throw an exception, the result will be returned with an exception. (thrown exception follows the last return task)
    5. There is also a InvokeAll method: Returns the future list of all tasks when all tasks are completed.
Example

Scenario Description: The following program simulates finding two user names (based on user name and password) in the database to obtain the fastest user to query.

/** * Created by Zhuqiang on 2015/8/30 0030. * * Public  class Client {     Public Static void Main(string[] args) {arraylist<task> list =NewArraylist<task> (); List.add (NewTask (NewUservalidator (),"Xiao Qiang","123456")); List.add (NewTask (NewUservalidator (),"Small and strong","123456")); List.add (NewTask (NewUservalidator (),"Small Little Strong","123456")); Threadpoolexecutor es = (threadpoolexecutor) Executors.newfixedthreadpool (2);Try{String s = es.invokeany (list);//Executes the given task, and returns the result if a task has completed successfully (that is, an exception was thrown). Once normal or abnormal returns, the unfinished task is canceled. If the given collection is modified while this operation is in progress, the result of this method is indeterminate. SYSTEM.OUT.PRINTLN (S +"main--user authentication through"); }Catch(Interruptedexception e)        {E.printstacktrace (); }Catch(Executionexception e)        {E.printstacktrace ();    } es.shutdown (); }}//user authentication object, used to simulate the process of querying in a databaseClass uservalidator{ Public Boolean Validator(String name,string password) {LongTime = (Long) (Math.random () *Ten);Try{TimeUnit.SECONDS.sleep (time); System.out.println ("Time-consuming ========="+ Thread.CurrentThread (). GetName () +"Time consuming:"+ time); }Catch(Interruptedexception e) {System.out.println ("Cancel ========="+thread.currentthread (). GetName () +"The task was interrupted");return false; }//return new Random (). Nextboolean (); Returns a random value. Indicates whether the identity passed is validated        return true;//Always returns TRUE. Used to verify that after the first one is found, the subsequent thread will be canceled.}}class Task implements callable<string>{PrivateUservalidator UV;PrivateString name;PrivateString password; Public Task(Uservalidator UV, string name, string password) { This. UV = UV; This. name = name; This. Password = password; }@Override     PublicStringPager()throwsException {if(!uv.validator (Name,password)) {//Not found, and throws an exceptionSystem.out.println ("User ========= not Found"+"Task:"+ Thread.CurrentThread (). GetName () +"   "+ name);Throw NewException ("The user was not found:"+ name); } System.out.println ("Find User ========="+"Task:"+ Thread.CurrentThread (). GetName () +"   "+ name);returnName }}

One run Result:

耗时=========pool-1-thread-2 耗时:1找到用户=========Task:pool-1-thread-2   小小强小小强   Main——用户验证通过取消=========pool-1-thread-2 该任务被中断没有找到用户=========Task:pool-1-thread-2   小小小小强取消=========pool-1-thread-1 该任务被中断没有找到用户=========Task:pool-1-thread-1   小强

Result Description
1. As you can see, after the first one is found, the result is returned and the unfinished task is interrupted.
2. Key point of this example Es.invokeany (list)

See if all the tasks are not returning results, they all throw exceptions.
Modify the above code so that all tasks throw an exception and get the result of one of the following runs:

Time Consuming =========pool-1-thread-1Take:3User =========task:pool-not found1-thread-1Cockroach Time =========pool-1-thread-1Take:0User =========task:pool-not found1-thread-1Small and small strong time =========pool-1-thread-2Take:6Java.util.concurrent.ExecutionException:java.lang.Exception: The user was not found: little strong did not find the user =========task:pool-1-thread-2Small strong at Java.util.concurrent.FutureTask.report (Futuretask.java:122) at Java.util.concurrent.FutureTask.get (Futuretask.java:192) at Java.util.concurrent.AbstractExecutorService.doInvokeAny (Abstractexecutorservice.java:193) at Java.util.concurrent.AbstractExecutorService.invokeAny (Abstractexecutorservice.java:215) at Java7Concurrency.sync4_4.Client.main (Client.java: -) at Sun.reflect.NativeMethodAccessorImpl.invoke0 (Native Method) at Sun.reflect.NativeMethodAccessorImpl.invoke (Nat Ivemethodaccessorimpl.java: +) at Sun.reflect.DelegatingMethodAccessorImpl.invoke (Delegatingmethodaccessorimpl.java: +) at Java.lang.reflect.Method.invoke (Method.java:497) at Com.intellij.rt.execution.application.AppMain.main (Appmain.java: $) caused by:java.lang.Exception: The user was not found: little strong at Java7Concurrency.sync4_4.Task.call (Client.java: -) at Java7Concurrency.sync4_4.Task.call (Client.java: $) at Java.util.concurrent.FutureTask.run (Futuretask.java:266) at Java.util.concurrent.executors$runnableadapter.call (Executors.java:511) at Java.util.concurrent.FutureTask.run (Futuretask.java:266) at Java.util.concurrent.ThreadPoolExecutor.runWorker (Threadpoolexecutor.java:1142) at Java.util.concurrent.threadpoolexecutor$worker.run (Threadpoolexecutor.java:617) at Java.lang.Thread.run (Thread.java:745)

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Notes [Java7 Concurrent Programming Manual]4.5 runs multiple tasks and processes the first result threadpoolexecutor

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.