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.module.spring.events;
8   
9   import edu.emory.mathcs.backport.java.util.concurrent.ExecutorService;
10  import edu.emory.mathcs.backport.java.util.concurrent.RejectedExecutionException;
11  
12  import org.apache.commons.logging.Log;
13  import org.apache.commons.logging.LogFactory;
14  import org.springframework.context.ApplicationEvent;
15  import org.springframework.context.ApplicationListener;
16  
17  /**
18   * <code>AsynchronousEventListener</code> will proces a received MuleEvent in a
19   * separate Thread. The thread pool passed in the constructor will determine how many
20   * threads can be executed at any time.
21   */
22  
23  public class AsynchronousEventListener implements MuleEventListener
24  {
25      /**
26       * logger used by this class
27       */
28      protected static final Log logger = LogFactory.getLog(AsynchronousEventListener.class);
29  
30      /**
31       * The listener to delegate to
32       */
33      private final ApplicationListener listener;
34  
35      /**
36       * the pool that manages the threads of execution
37       */
38      private final ExecutorService threadPool;
39  
40      public AsynchronousEventListener(ExecutorService threadPool, ApplicationListener listener)
41      {
42          this.threadPool = threadPool;
43          this.listener = listener;
44      }
45  
46      public void onApplicationEvent(ApplicationEvent event)
47      {
48          try
49          {
50              threadPool.execute(new Worker(listener, event));
51          }
52          catch (RejectedExecutionException e)
53          {
54              logger.error("Failed to execute worker for event: " + event.toString(), e);
55          }
56      }
57  
58      public ApplicationListener getListener()
59      {
60          return listener;
61      }
62  
63      private static class Worker implements Runnable
64      {
65          private final ApplicationListener listener;
66          private final ApplicationEvent event;
67  
68          public Worker(ApplicationListener listener, ApplicationEvent event)
69          {
70              this.listener = listener;
71              this.event = event;
72          }
73  
74          public void run()
75          {
76              try
77              {
78                  listener.onApplicationEvent(event);
79              }
80              catch (Exception e)
81              {
82                  logger.error("Failed to forward event: " + event.toString(), e);
83              }
84          }
85      }
86  
87  }