1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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
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 }