Notes [Java7 Concurrent Programming Manual]4.4 perform tasks in the actuator and return results callable, future

Source: Internet
Author: User

Notes [Java7 Concurrent Programming manual] series catalogue

Brief introduction

One of the advantages of the execution Framework (Executor framework) is that you can return results when running concurrent tasks. However, the following two classes are required to implement the functionality:
  
1. InterfaceCallable<V>

A task that returns the result and may throw an exception. The implementing person defines a method called call without any parameters.
The callable interface is similar to Runnable, and both are designed for classes whose instances might be executed by another thread. However, Runnable does not return a result and cannot throw a checked exception.
The Executors class contains some practical ways to convert from other common forms to callable classes.

简单说:就是实现这个类,并在唯一的call() 方法里面实现自己的业务逻辑。

2. InterfaceFuture<V>

The future represents the result of an asynchronous calculation. It provides a way to check whether the calculation is complete, to wait for the calculation to complete, and to get the results of the calculation. You can only use the Get method to get the results after the calculation is complete and, if necessary, block this method before the calculation is complete. Cancellation is performed by the Cancel method. Other methods are provided to determine whether the task is completed properly or canceled. Once the calculation is complete, you can no longer cancel the calculation. If you use the future for the sake of cancellation and do not provide the available results, you can declare the future <?> form type and return null as the result of the underlying task.

简单说:该接口可以获取一个线程的结果。调用get的时候,如果结果没有计算完成,则阻塞。这个接口我觉得得好好理解下,在使用谷歌的AsyncHttpClient 异步的同步支持http Client的时候,里面就是使用 future来作为返回结果。利用它就能异步的请求和推送结果。

Use Google's asynchttpclient to simply mimic the asynchttpclient of Android and implement the return value of the asynchronous request callback function
In this chapter, you will learn how to implement the return results of a task and run the task in the executor.

Callable and future use of this chapter
    1. Callable and runnable are similar, except that callable can return results.
    2. The run in the callable will not throw an exception before Future.get (), and Future.isdone () will return ture, whether or not it runs normally or throws an exception.
    3. Threadpoolexecutor.getcompletedtaskcount () is the number of tasks that are returned to completion, which refers to the Future.isdone () of ture.
      4. A simple sentence: As long as the callable task to the executor execution, and then wait for the results to be done, in the execution of some do not need to block the running results of the scene costs apply.

Finally, a question: in Google's asynchttpclient, asynchttpclient.boundrequestbuilder builder = http.preparepost (URL); Future F = Builder.execute (); In the code, the contents of the task without calling the Future.get () are not executed, that is, before the Get () method is called, the HTTP request is not sent out. About this question. I suspect that there is probably no reason to run the line pool with a similar actuator. The specific reasons for the time to see the source code to know. If you know, you can tell me.

Example

Scenario Description: The following example illustrates the use of the Callable Task Class task, which executes inside what is returned outside, using the sleep to simulate the time of the operation. The created callable is then handed to the actuator for execution. Get the Future object, then use Future.get () to get the results

/** * Created by Zhuqiang on 2015/8/30 0030. * * Public  class Client {     Public Static void Main(string[] args)throwsExecutionexception, interruptedexception {arraylist<future<integer>> list =NewArraylist<future<integer>> (); Threadpoolexecutor ex = (threadpoolexecutor) Executors.newfixedthreadpool (3); for(inti =0; I <5; i++) {Task task =NewTask (i); future<integer> f = ex.submit (Task);//Callable task to thread to run,List.add (f);//Collect the future objects. Get Results} ex.shutdown ();//through Isdone to get the completion status of the task. IsDone: Returns True if the task is completed. This method returns true in all of these cases, possibly due to a normal termination, exception, or cancellation. do { for(inti =0; I < list.size (); i++) {future<integer> f = list.get (i);if(F.isdone ()) {System.out.printf ("main_task_%s task completed:%s\n"Itrue); }} TimeUnit.MILLISECONDS.sleep ( -);//Hibernate 500 ms} while(Ex.getcompletedtaskcount () < list.size ());//When the number of tasks completed in the executor is less than the target quantity. The completion of the task is always recycled        //When All tasks are completed, the returned results will be printedSystem.out.println ("\ n----------------------Main result--------------------------------\ n"); for(inti =0; I < list.size ();            i++) {future<integer> f = list.get (i); System.out.printf ("The result of main_task_%s is:%s\n", I, F.get ());//Because the Get () method is complete if the thread has not yet been evaluated. will block until the result is returned. So, instead of using get to get the result directly, we get the task completion state inside the actuator and observe the task running condition.}}}class Task implements callable<integer>{ Public intNum Public Task(intNUM) { This. num = num; }@Override     PublicIntegerPager()throwsException {LongTime = (Long) (Math.random () *Ten); TimeUnit.SECONDS.sleep (time);//if (1 = = num) {//actually: I want to test, when executing in the executor, whether the task really executes, this makes me very confused. Because in the business I've done: asynchronously sends an HTTP request and uses the future to send it. But if I do not call get (), then there is no request to be sent. And then test it here, without calling get , it did.//throw new RuntimeException ("Test throws Exception");//        }System.out.printf ("%s was dormant for%s seconds \ n", Thread.CurrentThread (). GetName (), time);returnNum }}

The result of a run:

pool-1-thread-3Dormant.3Seconds main_task_2 The task is complete:trueMain_task_2 the task is complete:trueMain_task_2 the task is complete:trueMain_task_2 the task is complete:trueMain_task_2 the task is complete:truepool-1-thread-1Dormant.6SEC pool-1-thread-2Dormant.6Seconds Main_task_0 The task is complete:trueMain_task_1 the task is complete:trueMain_task_2 the task is complete:truepool-1-thread-3Dormant.3Seconds Main_task_0 The task is complete:trueMain_task_1 the task is complete:trueMain_task_2 the task is complete:trueMain_task_3 the task is complete:trueMain_task_0 the task is complete:trueMain_task_1 the task is complete:trueMain_task_2 the task is complete:trueMain_task_3 the task is complete:trueMain_task_0 the task is complete:trueMain_task_1 the task is complete:trueMain_task_2 the task is complete:trueMain_task_3 the task is complete:trueMain_task_0 the task is complete:trueMain_task_1 the task is complete:trueMain_task_2 the task is complete:trueMain_task_3 the task is complete:trueMain_task_0 the task is complete:trueMain_task_1 the task is complete:trueMain_task_2 the task is complete:trueMain_task_3 the task is complete:truepool-1-thread-1Dormant.3Seconds----------------------The result of the Main result--------------------------------Main_task_0 is:0The result of Main_task_1 is:1The result of Main_task_2 is:2The result of Main_task_3 is:3The result of Main_task_4 is:4

Result Description:
You can see the results of the above running, and when we give the task to the executor, it is actually running in a thread way. After all tasks have been completed, you can get the correct return result. If we open the exception above, we can see that even if the program throws an exception, it will not throw an exception until the get () is called. The task completion state is then consistent with the JDK description, which is true

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

Notes [Java7 Concurrent Programming Manual]4.4 perform tasks in the actuator and return results callable, future

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.