Java CountDownLatch expects timeout value when thread.run () counting latch gets an exception

I am using CountDownLatch to handle two Java threads. My class structure is as follows:

MainClass.java
ThreadOne.java
ThreadTwo.java

MainClass:

 CountDownLatch latch = new CountDownLatch(2); Thread thread = new Thread(new ThreadOne(latch)); thread.start(); Thread thread1 = new Thread(new ThreadTwo(latch)); thread1.start(); latch.await(20, TimeUnit.SECONDS); 

The main class waits until the other two threads finish their work. Once they complete their work, it does not wait for its timeout value (20 seconds). My problem is that if any of the threads gets destroyed or corrupted, then CountDownLatch expects its timeout value. Is there a way to ignore this intermittent flow and move forward without waiting 20 seconds?

+5
source share
2 answers

zapl is absolutely right! The main thread is waiting for a timeout. If you took a stream dump while waiting for the main stream on the latch, you will see something like:

 "main" #1 prio=5 os_prio=31 tid=0x00007fa4be002000 nid=0x1303 waiting on condition [0x000000010b74c000] java.lang.Thread.State: TIMED_WAITING (parking) at sun.misc.Unsafe.park(Native Method) - parking to wait for <0x000000076abcb598> (a java.util.concurrent.CountDownLatch$Sync) at java.util.concurrent.locks.LockSupport.parkNanos(LockSupport.java:215) at java.util.concurrent.locks.AbstractQueuedSynchronizer.doAcquireSharedNanos(AbstractQueuedSynchronizer.java:1037) at java.util.concurrent.locks.AbstractQueuedSynchronizer.tryAcquireSharedNanos(AbstractQueuedSynchronizer.java:1328) at java.util.concurrent.CountDownLatch.await(CountDownLatch.java:277) 

From Javadoc await :

If the current counter is greater than zero, then the current thread is turned off for thread scheduling purposes and is at rest until one of three things happens:

  • The count reaches zero due to calls to the countDown method; or
  • Some other threads interrupt the current thread; or
  • The specified timeout expires.

In your case, the await call returns only because of 3).

In the CountDownLatch Javadoc, the call to the countDown() method must be executed in the finally block:

 public void run() { try { startSignal.await(); doWork(); // may throw exception } catch (InterruptedException ex) { // handle interruption ... } finally { doneSignal.countDown(); // cause await to return asap } } 
+6
source

You need some kind of notification when the thread is destroyed. One way to do this is to InterruptedException manually in the stream, and then calculate the error.

Another way is to use Runnable tasks instead of Threads and use guavas ListenableFuture to receive error notifications. This SO Q&A explains this well.

0
source

All Articles