KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > mule > extras > spring > events > AsynchronousEventListener


1 /*
2  * $Id: AsynchronousEventListener.java 3798 2006-11-04 04:07:14Z aperepel $
3  * --------------------------------------------------------------------------------------
4  * Copyright (c) MuleSource, Inc. All rights reserved. http://www.mulesource.com
5  *
6  * The software in this package is published under the terms of the MuleSource MPL
7  * license, a copy of which has been included with this distribution in the
8  * LICENSE.txt file.
9  */

10
11 package org.mule.extras.spring.events;
12
13 import org.apache.commons.logging.Log;
14 import org.apache.commons.logging.LogFactory;
15 import org.springframework.context.ApplicationEvent;
16 import org.springframework.context.ApplicationListener;
17
18 import edu.emory.mathcs.backport.java.util.concurrent.ExecutorService;
19 import edu.emory.mathcs.backport.java.util.concurrent.RejectedExecutionException;
20
21 /**
22  * <code>AsynchronousEventListener</code> will spawn a thread for each Event
23  * received. The thread pool passed in the constructor will determine hown many
24  * threads can be executed at any time.
25  */

26
27 public class AsynchronousEventListener implements MuleEventListener
28 {
29     /**
30      * logger used by this class
31      */

32     protected static Log logger = LogFactory.getLog(AsynchronousEventListener.class);
33
34     /**
35      * The listener to delegate to
36      */

37     private final ApplicationListener listener;
38
39     /**
40      * the pool that manages the threads of execution
41      */

42     private final ExecutorService threadPool;
43
44     public AsynchronousEventListener(ExecutorService threadPool, ApplicationListener listener)
45     {
46         this.threadPool = threadPool;
47         this.listener = listener;
48     }
49
50     public void onApplicationEvent(ApplicationEvent event)
51     {
52         try
53         {
54             threadPool.execute(new Worker(event));
55         }
56         catch (RejectedExecutionException e)
57         {
58             logger.error("Failed to process event: " + event.toString(), e);
59         }
60     }
61
62     private class Worker extends Thread JavaDoc
63     {
64         private ApplicationEvent event;
65
66         public Worker(ApplicationEvent event)
67         {
68             this.event = event;
69         }
70
71         public void run()
72         {
73             listener.onApplicationEvent(event);
74         }
75     }
76
77     public ApplicationListener getListener()
78     {
79         return listener;
80     }
81 }
82
Popular Tags