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