title: Unable to test java.util.Timer using Junit along with CountDownLatch
body: <p>I am using a timer to perform some operation repetitively every 2 seconds. I am using JUnit to test this timer method. </p>
  
  <p>Normally if I call the timer method, it just runs once and exits without giving me the actual results. But if I use the CountDownLatch, I get the expected result but the test never terminates or passes, it keeps on waiting for something even though the expected result is already obtained.</p>
  
  <p>Is there a way to get around this problem or cancelling the CountDownLatch after some criterion is met? </p>
  
  <p>Below is my code for the timer class and the JUnit test:</p>
  
  <pre><code>public class TimerTest {
  int count=0;    
  private  Timer timer = new Timer();     
  
  void doSomething() {  
      timer.schedule(new TimerTask() {
          public void run() {
              doSomethingElse();  
          }
      },
      1000, 2000);   
  
  }
  
  private  void doSomethingElse(){
      count++;
      System.out.println("the count is "+count);
      if(count&gt;5){
          timer.cancel();
          timer.purge();
      }
  
  
  }
  
  }
  </code></pre>
  
  <p>Below is the Junit:</p>
  
  <pre><code>public class JunitTimer {
  @Test
  public void test() throws InterruptedException {
  
  
       TimerTest test = new TimerTest();
       final CountDownLatch latch = new CountDownLatch(2);        
     test.doSomething();
     latch.countDown();
  
  
     System.out.println("LCountdown is " +latch.getCount());
      latch.await();
  
  
  }
  }
  </code></pre>