01: /*
02: * $Id: AsynchronousEventListener.java 10789 2008-02-12 20:04:43Z dfeist $
03: * --------------------------------------------------------------------------------------
04: * Copyright (c) MuleSource, Inc. All rights reserved. http://www.mulesource.com
05: *
06: * The software in this package is published under the terms of the CPAL v1.0
07: * license, a copy of which has been included with this distribution in the
08: * LICENSE.txt file.
09: */
10:
11: package org.mule.module.spring.events;
12:
13: import edu.emory.mathcs.backport.java.util.concurrent.ExecutorService;
14: import edu.emory.mathcs.backport.java.util.concurrent.RejectedExecutionException;
15:
16: import org.apache.commons.logging.Log;
17: import org.apache.commons.logging.LogFactory;
18: import org.springframework.context.ApplicationEvent;
19: import org.springframework.context.ApplicationListener;
20:
21: /**
22: * <code>AsynchronousEventListener</code> will proces a received MuleEvent in a
23: * separate Thread. The thread pool passed in the constructor will determine how many
24: * threads can be executed at any time.
25: */
26:
27: public class AsynchronousEventListener implements MuleEventListener {
28: /**
29: * logger used by this class
30: */
31: protected static final Log logger = LogFactory
32: .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,
45: ApplicationListener listener) {
46: this .threadPool = threadPool;
47: this .listener = listener;
48: }
49:
50: public void onApplicationEvent(ApplicationEvent event) {
51: try {
52: threadPool.execute(new Worker(listener, event));
53: } catch (RejectedExecutionException e) {
54: logger.error("Failed to execute worker for event: "
55: + event.toString(), e);
56: }
57: }
58:
59: public ApplicationListener getListener() {
60: return listener;
61: }
62:
63: private static class Worker implements Runnable {
64: private final ApplicationListener listener;
65: private final ApplicationEvent event;
66:
67: public Worker(ApplicationListener listener,
68: ApplicationEvent event) {
69: this .listener = listener;
70: this .event = event;
71: }
72:
73: public void run() {
74: try {
75: listener.onApplicationEvent(event);
76: } catch (Exception e) {
77: logger.error("Failed to forward event: "
78: + event.toString(), e);
79: }
80: }
81: }
82:
83: }
|