Executors Future Callable Instance

Source: Internet
Author: User

From: Https://www.cnblogs.com/shipengzhi/articles/2067154.html:java concurrent programming-executor Framework +future

Importjava.util.concurrent.*; Public classConcurrentCalculator2 {PrivateExecutorservice Executorservice; PrivateCompletionservice<long>Completionservice; Private intCpucorenumber;  PublicConcurrentCalculator2 () {Cpucorenumber=runtime.getruntime (). Availableprocessors (); Executorservice=Executors.newfixedthreadpool (Cpucorenumber); Completionservice=NewExecutorcompletionservice<long>(Executorservice); }     PublicLong sum (Final int[] numbers) {         for(inti = 0; i < Cpucorenumber; i++) {//split tasks based on number of CPU cores, create futuretask and submit to executor            intincrement = Numbers.length/cpucorenumber + 1; intstart = increment *i; intend = Increment * i +increment; if(End >numbers.length) End=numbers.length; Sumcalculator Subcalc=Newsumcalculator (numbers, start, end); if(!Executorservice.isshutdown ())            {Completionservice.submit (SUBCALC); }        }        returnGetResult (); }     PublicLong GetResult () {//iterate through each task, get part sum, and add backLong result = 0l;  for(inti = 0; i < Cpucorenumber; i++) {            Try{Long subsum=Completionservice.take (). get (); Result+=subsum; } Catch(interruptedexception e) {e.printstacktrace (); } Catch(executionexception e) {e.printstacktrace (); }        }        returnresult; }     Public voidClose () {Executorservice.shutdown (); }    classSumcalculatorImplementscallable<long> {//Runnable        Private int[] numbers; Private intstart; Private intend;  PublicSumcalculator (Final int[] numbers,intStartintend) {             This. Numbers =numbers;  This. Start =start;  This. end =end; } @Override PublicLong Call ()throwsException {Long sum= 0l;  for(inti = start; I < end; i++) {sum+=Numbers[i]; }            returnsum; }    }     Public Static voidMain (string[] args) {int[] numbers =New int[] {0, 1, 2, 3, 4, 5, 6, 7, 8  }; ConcurrentCalculator2 Calculator=NewConcurrentCalculator2 (); Long sum=calculator.sum (numbers);        SYSTEM.OUT.PRINTLN (sum);    Calculator.close (); }    /*** Callable and future interfaces * Callable are similar to runnable interfaces, classes that implement callable interfaces, and classes that implement runnable, are tasks that can be performed by other threads.     * There are several differences between callable and runnable: * (1) The method prescribed by callable is call (), and the Runnable method is run ().     * (2) callable can return a value after a task is executed, and Runnable's task cannot return a value.     * (3) The call () method throws an exception, and the run () method cannot throw an exception. * (4) Run the callable task to get a future object, * the future represents the result of an asynchronous calculation.     It provides a way to check whether the calculation is complete, to wait for the completion of the calculation, and to retrieve the results of the calculation.     * The future object can be used to understand task execution, cancel the execution of the task, and get the result of the task execution. */}

Https://www.jb51.net/article/132606.htm:

We all know that there are 2 ways to implement multithreading, one is to inherit thread, one is to implement runnable, but there is a flaw in all 2 ways that the returned result cannot be obtained after the task is completed. To get the return result, you have to use the callable,callable task to have a return value, but you cannot get the return value directly from the callable task; to get the return value of the Callabel task, you need to use the future. So the callable task and the future pattern are usually combined to use.

Imagine a scenario where you need a post list interface, in addition to returning a list of posts, you need to return a list of likes and comments for each post. A page of 10 posts to calculate, this interface needs to access 21 databases, access to a database by 100ms calculation, 21 times, the cumulative time is 2.1s. This response time, I am afraid is not satisfactory. What do we do? Asynchronous transformation interface.

After you find the list of posts, iterate through the list of posts, 10 threads in the loop, get a list of likes for each post, and another 10 threads, and get a list of comments for each post. After this transformation, the response time of the interface is greatly shortened, at 200ms. This time will be used Callabel combined with the future to achieve.

PrivateList<postresponse> createpostresponselist (page<postresponse> Page,FinalString userId) {     if(Page.getcount () ==0| | page==NULL|| Page.getlist () = =NULL){       return NULL; }     //get a list of postsList<postresponse> circleresponselist =page.getlist (); intSitescircleresponselist.size (); Executorservice Commentpool=executors.newfixedthreadpool (size); Executorservice Supportpool=executors.newfixedthreadpool (size); Try{List<Future> commentfuturelist =NewArraylist<future>(size); if(Circleresponselist! =NULL&& circleresponselist.size () > 0) {          for(Postresponse postresponse:circleresponselist) {FinalString circleid=Postresponse.getid (); FinalString postuserid=Postresponse.getuserid (); //Check the list of commentsCallable<list<circlereviews>> callablecomment =NewCallable<list<circlereviews>>() {@Override PublicList<circlereviews> Call ()throwsException {returncirclereviewsbiz.getpostcomments (CircleID);           }           }; Future F=Commentpool.submit (callablecomment);           Commentfuturelist.add (f); //List of likesCallable<list<circlezan>> Callablesupport =NewCallable<list<circlezan>>() {@Override PublicList<circlezan> Call ()throwsException {returncirclezanbiz.findlist (CircleID);           }           }; Future Supportfuture=Supportpool.submit (Callablesupport);         Commentfuturelist.add (supportfuture); }         }       //get execution results for all concurrent tasks      inti = 0; Postresponse Temp=NULL;  for(future f:commentfuturelist) {temp=Circleresponselist.get (i); Temp.setcommentlist (List<CircleReviews>) F.get (); Temp.setsupportlist (List<CircleZan>) F.get ();         Circleresponselist.set (i, temp); I++; }       } Catch(Exception e) {e.printstacktrace (); } finally {       //Close the thread poolCommentpool.shutdown ();     Supportpool.shutdown (); }     returncircleresponselist;}

★ Below is a sample code (17465497?UTM_SOURCE=BLOGXGWZ0) to perform the callable task executor:

Importjava.util.ArrayList;Importjava.util.List;Importjava.util.concurrent.*;  Public classcallabledemo{ Public Static voidMain (string[] args) {Executorservice Executorservice=Executors.newcachedthreadpool (); List<Future<String>> resultlist =NewArraylist<future<string>>(); //Create 10 of tasks and execute         for(inti = 0; I < 10; i++){             //use Executorservice to perform callable types of tasks and save the results in future variablesfuture<string> future = Executorservice.submit (NewTaskwithresult (i)); //to store task execution results in a listResultlist.add (future); }          //traverse the results of a task         for(future<string>fs:resultlist) {                 Try{                      while(!fs.isdone);//Future returns if not completed, wait until the future returns to completionSystem.out.println (Fs.get ());//Print the results of each thread (Task) execution}Catch(interruptedexception e) {e.printstacktrace (); }Catch(executionexception e) {e.printstacktrace (); }finally{                     //start a sequential shutdown, perform a previously submitted task, but not accept a new taskExecutorservice.shutdown (); }         }     } }   classTaskwithresultImplementsCallable<string>{     Private intID;  PublicTaskwithresult (intID) {          This. ID =ID; }      /*** The specific process of the task, once the task is passed to Executorservice's Submit method, the method automatically executes on one thread*/      PublicString Call ()throwsException {System.out.println (The call () method is automatically called!!! " +Thread.CurrentThread (). GetName ()); //The return result will be obtained by the Get method of the future        returnThe call () method is called automatically, and the result returned by the task is: "+ ID +" "+Thread.CurrentThread (). GetName (); } }

A result of the execution is as follows:

As can be seen from the results, submit also selects the idle thread to perform the task first, and if not, creates a new thread to perform the task. Also, note that if the return of the future is not yet complete, the Get () method blocks the wait until the future completes the return, and can be used to determine whether the future is completed by calling the Isdone () method.

Executors Future Callable Instance

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.