Java completes asynchronous callbacks with Countdownlatch

Source: Internet
Author: User

 Public   class   asyncdemo  { Private      static void dosometask ()  {System.out.println ("Hello World"); } Private      static void oncompletion ()  {System.out.println ("All Tasks finished"); }       public static void Main (string[]  args)   {Executorservice executor = Executors.newcachedthreadpool ();FinalCountdownlatch latch =NewCountdownlatch (2); Executor.execute (NewTask (latch)); Executor.execute (NewTask (latch)); Executor.execute ((), {Try{latch.await (); }Catch(Interruptedexception e)            {E.printstacktrace ();        } oncompletion ();        });    Executor.shutdown (); }Private Static  class       Task implements   Runnable  {/** * Countdownlatch is a simple thread monitoring tool provided by the JDK * based on a simple count, calling the countdown () method to indicate that the current thread has terminated * call await in the monitoring thread () Method, the method is suspended until all other threads are terminated.        Private FinalCountdownlatch latch;Public Task   (countdownlatch latch)    { This. latch = latch; }@Override                public void Run( ) {Try{Dosometask (); }Catch(Exception e)            {E.printstacktrace (); }finally{Latch.countdown (); }        }    }}

Here are two points to add:

1. If you are a thread that is started with the main method, this method of invocation is not a problem, and the JDK will ensure that all threads terminate after the main method exits. However, if the main method is not the initiator of an asynchronous task (such as Junit,spring,tomcat), Laucher will lose control of the thread once it is started. As in JUnit, Laucher is considered complete after the task has been committed and other threads are forcibly terminated.

2. For this reason, please use the correct executor according to the environment. For example, in a Web environment, a tomcat (or spring)-managed thread pool should be used as a executor to ensure that the Web application has control over the entire life cycle of the asynchronous task; What happens if you use the thread pool of the JDK? The task may execute normally, and when you terminate Web-app, the asynchronous thread being executed will not be killed normally, causing a memory leak or other unforeseen consequences.


the thread in Executors.newcachedthreadpool () is Isdaemon true.
I've been working on it for 13 years and I've studied the use of countdownlatch coordination threads http://unmi.cc/countdownlatch-threads/.
Countdownlatch is a Java 1.5 added API, to Java 8 I will choose to use completablefuture, it to wait for all threads to complete can be simply called
Completablefuture.allof (completablefuture...completablefutures)
is the mechanism of the WAITALL () of other frameworks.



Java completes asynchronous callbacks with Countdownlatch

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.