View Javadoc

1   /*
2    * $Id: EventProcessingThread.java 22666 2011-08-15 06:35:36Z mike.schilling $
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  package org.mule.routing;
11  
12  import org.apache.commons.logging.Log;
13  import org.apache.commons.logging.LogFactory;
14  
15  
16  /**
17   * A thread that detects and processes events.
18   */
19  public abstract class EventProcessingThread extends Thread
20  {
21      protected final Log logger = LogFactory.getLog(EventProcessingThread.class);
22  
23      protected volatile boolean stopRequested;
24      protected long delayTime;
25      protected Object lock = new Object();
26  
27      public EventProcessingThread(String name, long delayTime)
28      {
29          setName(name);
30          this.delayTime = delayTime;
31      }
32  
33      public void processNow()
34      {
35          synchronized (lock)
36          {
37              lock.notifyAll();
38          }
39      }
40      
41      /**
42       * Stops the monitoring of the expired groups.
43       */
44      public void stopProcessing()
45      {
46          logger.debug("Stopping expiring group monitoring");
47          stopRequested = true;
48          processNow();
49          
50          try
51          {
52              this.join();
53          }
54          catch (InterruptedException e)
55          {
56              // Ignoring
57          }
58      }
59  
60      protected boolean delay(long timeToDelay)
61      {
62          try
63          {
64              synchronized (lock)
65              {
66                  lock.wait(timeToDelay);
67              }
68          }
69          catch (InterruptedException e)
70          {
71              return true;
72          }
73          return false;
74      }
75  
76      public final void run()
77      {
78          while (true)
79          {
80              if (stopRequested)
81              {
82                  logger.debug("Received request to stop processing events");
83                  break;
84              }
85              doRun();
86              if (delay(delayTime))
87              {
88                  break;
89              }
90          }
91  
92          logger.debug("Expiring group monitoring fully stopped");
93      }
94  
95      /**
96       * Detect and process events
97       */
98      protected abstract void doRun();
99  
100 }