33import java .util .*;
44import javaxt .utils .Value ;
55import javaxt .express .utils .DateUtils ;
6+ import java .util .concurrent .atomic .AtomicBoolean ;
7+
68
79//******************************************************************************
810//** NotificationService
1416
1517public class NotificationService {
1618
17- private static List events = null ;
18- private static List <Listener > listeners ;
19+ private static List events = new LinkedList ();
20+ private static List <Listener > listeners = new LinkedList ();
21+ private static AtomicBoolean isRunning = new AtomicBoolean (false );
1922
2023
2124 //**************************************************************************
@@ -27,7 +30,7 @@ public class NotificationService {
2730 * @param data Additional information related to the event (e.g. User ID)
2831 */
2932 public static void notify (String event , String model , Value data ){
30- if (events == null ) return ;
33+ if (! isRunning . get () ) return ;
3134
3235 if (data ==null ) data = new Value (null );
3336
@@ -49,15 +52,14 @@ public static void start(){
4952 }
5053
5154 public static void start (int numThreads ){
52- if (events != null ) return ;
55+ if (isRunning . get () ) return ;
5356
54- listeners = new LinkedList ();
5557
56- events = new LinkedList ();
5758 for (int i =0 ; i <numThreads ; i ++){
5859 Thread thread = new Thread (new NotificationProcessor ());
5960 thread .start ();
6061 }
62+ isRunning .set (true );
6163 }
6264
6365
@@ -78,16 +80,22 @@ public static void stop(){
7880 events .add (0 , null );
7981 events .notify ();
8082 }
81- events = null ;
8283 }
8384
8485
8586 //**************************************************************************
8687 //** addListener
8788 //**************************************************************************
88- /** Used to add an event listener that will consume events
89+ /** Used to add an event listener that will consume events. Example:
90+ <pre>
91+ NotificationService.addListener((
92+ String event, String model, javaxt.utils.Value data, long timestamp)->{
93+ console.log(event, model, data);
94+ });
95+ </pre>
8996 */
9097 public static void addListener (Listener listener ){
98+ if (!isRunning .get ()) return ;
9199 synchronized (listeners ){
92100 listeners .add (listener );
93101 listeners .notify ();
@@ -139,6 +147,7 @@ public void run() {
139147
140148 }
141149 else {
150+ isRunning .set (false );
142151 return ;
143152 }
144153 }
0 commit comments