View Javadoc

1   /*
2    *  Copyright (C) 2003-2005 SINTEF
3    *  Author:  Fredrik Vraalsen (fredrik dot vraalsen at sintef dot no)
4    *  Webpage: http://coras.sourceforge.net/
5    *
6    *  This program is free software; you can redistribute it and/or
7    *  modify it under the terms of the GNU Lesser General Public License
8    *  as published by the Free Software Foundation; either version 2.1
9    *  of the License, or (at your option) any later version.
10   *
11   *  This program is distributed in the hope that it will be useful,
12   *  but WITHOUT ANY WARRANTY; without even the implied warranty of
13   *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14   *  Lesser General Public License for more details.
15   *
16   *  You should have received a copy of the GNU Lesser General Public
17   *  License along with this program; if not, write to the Free
18   *  Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
19   *  02111-1307 USA
20   */
21  package no.sintef.event;
22  
23  /***
24   * Event concentrator reduces overhead of many rapid events by collecting
25   * multiple events within a time window, firing only a single event once the
26   * time window elapses.
27   * 
28   * @author Fredrik Vraalsen
29   */
30  public class Concentrator {
31  
32  	private int windowLength;
33  	private Runnable eventHandler;
34  	private boolean waiting = false;
35  	
36  	/***
37  	 * Concentrator constructor.
38  	 * 
39  	 * @param windowLength
40  	 *            length of time window used for collecting events
41  	 * @param eventHandler
42  	 *            the event handler to activate once the time window has elapsed
43  	 */
44  	public Concentrator(int windowLength, Runnable eventHandler) {
45  		this.windowLength = windowLength;
46  		this.eventHandler = eventHandler;
47  	}
48  	
49  	/***
50  	 * If event is already queued, just return, otherwise start new thread and
51  	 * wait for specified time window before firing event.
52  	 */
53  	public final synchronized void fireEvent() {
54  		if (waiting) {
55  			return;
56  		}
57  		setWaiting(true);
58  		Thread runThread = new Thread() {
59  			public void run() {
60  				try {
61  					sleep(windowLength);
62  				} catch (InterruptedException e) {
63  					// TODO Auto-generated catch block
64  					e.printStackTrace();
65  				}
66  				setWaiting(false);
67  				eventHandler.run();
68  			}
69  		};
70  		runThread.start();
71  	}
72  
73  	/***
74  	 * Used to synchronize threads on waiting state.
75  	 * 
76  	 * @param b
77  	 *            new waiting state
78  	 */
79  	private synchronized void setWaiting(boolean b) {
80  		waiting = b;
81  	}
82  	
83  }