View Javadoc

1   /*
2    * $Id: TestCaseWatchdog.java 20321 2010-11-24 15:21:24Z dfeist $
3    * --------------------------------------------------------------------------------------
4    * Copyright (c) MuleSoft, Inc.  All rights reserved.  http://www.mulesoft.com
5    *
6    * The software in this package is published under the terms of the CPAL v1.0
7    * license, a copy of which has been included with this distribution in the
8    * LICENSE.txt file.
9    */
10  
11  package org.mule.tck;
12  
13  import edu.emory.mathcs.backport.java.util.concurrent.TimeUnit;
14  import edu.emory.mathcs.backport.java.util.concurrent.atomic.AtomicInteger;
15  
16  import org.apache.commons.logging.Log;
17  import org.apache.commons.logging.LogFactory;
18  
19  public class TestCaseWatchdog extends Thread
20  {
21      protected static final AtomicInteger threadNumber = new AtomicInteger(0);
22  
23      protected final Log log = LogFactory.getLog(getClass());
24  
25      protected final long delay;
26      protected final TimeUnit unit;
27      protected final TestCaseWatchdogTimeoutHandler handler;
28      protected volatile boolean timedOut = false;
29  
30      public TestCaseWatchdog(long delay, TimeUnit unit, TestCaseWatchdogTimeoutHandler timeoutHandler)
31      {
32          super("WatchdogThread-" + threadNumber.getAndIncrement());
33          this.setDaemon(true);
34          this.delay = delay;
35          this.unit = unit;
36          this.handler = timeoutHandler;
37      }
38  
39      public void run()
40      {
41          if (this.delay < 0)
42          {
43              return;
44          }
45          
46          long millisToWait = this.unit.toMillis(this.delay);
47          if (log.isDebugEnabled())
48          {
49              log.debug("Starting with " + millisToWait + "ms timeout.");
50          }
51  
52          try
53          {
54              Thread.sleep(millisToWait);
55              timedOut = true;
56              if (handler != null)
57              {
58                  handler.handleTimeout(delay, unit);
59              }
60          }
61          catch (InterruptedException interrupted)
62          {
63              if (log.isDebugEnabled())
64              {
65                  log.debug("Watchdog stopped.");
66              }
67          }
68      }
69  
70      public void cancel()
71      {
72          this.interrupt();
73      }
74  
75      public boolean isTimedOut()
76      {
77          return timedOut;
78      }
79  }