Java concurrent programming Callable and Future application instance code, callable application instance

Source: Internet
Author: User

Java concurrent programming Callable and Future application instance code, callable application instance

This article mainly explores the use of java concurrent programming callable and future and shares the related instance code. The details are as follows.

We all know that there are two ways to implement multithreading. One is to inherit the Thread and the other is to implement Runnable. However, there is a defect in both methods, and the returned results cannot be obtained after the task is completed. To obtain the returned results, you must use Callable. The Callable task can return values but cannot directly obtain the returned values from the Callable task. To obtain the return values of the Callabel task, you must use Future. Therefore, the Callable task and the Future mode are usually used in combination.

Imagine a scenario: a post list interface is required. In addition to returning the post list, you also need to return the like list and comment list for each post. Ten posts on one page are used for calculation. This interface requires 21 accesses to the database. One Access to the database is calculated in 2.1 Ms, 21 times, and the total time is s. This response time may not be satisfactory. What should we do? Asynchronous transformation interface.

After finding out the post list, iterate the post list, set up 10 threads in the loop, and concurrently obtain the liked list for each post, and set up another 10 threads, concurrently obtain the Comments List of each post. After this transformation, the response time of the interface is greatly shortened, in 200 ms. At this time, we need to use Callabel and Future.

Private List <PostResponse> createPostResponseList (Page <PostResponse> page, final String userId) {if (page. getCount () = 0 | page = null | page. getList () = null) {return null;} // obtain the post List <PostResponse> circleResponseList = page. getList (); int size = circleResponseList. size (); ExecutorService commentPool = Executors. newFixedThreadPool (size); ExecutorService supportPool = Executors. newFixedThreadPool (size ); Try {List <Future> commentFutureList = new ArrayList <Future> (size); if (circleResponseList! = Null & circleResponseList. size ()> 0) {for (PostResponse postResponse: circleResponseList) {final String circleId = postResponse. getId (); final String postUserId = postResponse. getUserId (); // query the Comments List Callable <List <CircleReviews> callableComment = new Callable <List <CircleReviews> () {@ Override public List <CircleReviews> call () throws Exception {return circleReviewsBiz. getPostComments (circleId) ;}}; Future f = commentPool. submit (callableComment); commentFutureList. add (f); // query the like List Callable <List <CircleZan> callableSupport = new Callable <List <CircleZan> () {@ Override public List <CircleZan> call () throws Exception {return circleZanBiz. findList (circleId) ;}}; Future supportFuture = supportPool. submit (callableSupport); commentFutureList. add (supportFuture) ;}// obtain the execution result of all concurrent tasks int I = 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 pool commentPool. shutdown (); supportPool. shutdown ();} return circleResponseList ;}

Summary

The above is all the content about the code of the Java concurrent programming Callable and Future application instance. I hope it will be helpful to you. If you are interested, you can continue to refer to other related topics on this site. If you have any shortcomings, please leave a message. Thank you for your support!

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.