View Javadoc

1   package org.lsst.ccs.utilities.dispatch;
2   
3   import java.util.concurrent.CopyOnWriteArrayList;
4   import java.util.concurrent.ExecutorService;
5   import java.util.logging.Level;
6   
7   /**
8    * An <TT>Observable</TT> that notifies <TT>Observers</TT>
9    * through an <TT>ExecutorService</TT> (that is through different threads).
10   *
11   * @author bernard AMADE
12   */
13  public class ParallelObservable<P> {
14      protected CopyOnWriteArrayList<ASyncObserver<P>> list = new CopyOnWriteArrayList<ASyncObserver<P>>() ;
15  
16       static class DoUpdate<P2> implements Runnable {
17          public final  ASyncObserver<P2> executant ;
18          public final P2 data ;
19  
20          DoUpdate(ASyncObserver<P2> executant, P2 data) {
21              this.executant = executant;
22              this.data = data ;
23          }
24  
25          @Override
26          public void run() {
27              try{
28                  executant.update(data);
29              } catch (Exception exc) {
30                 PackCst.CURLOG.log(Level.SEVERE, "while executing :", exc);
31              }
32          }
33      }
34  
35  
36      /**
37       *   ExecutorService that deals with the Threads handling the commands.
38       */
39      protected ExecutorService loop ;
40  
41  
42      /**
43       * Here the threads handling the updates are <TT>daemons</TT>.
44       * You may change that by using a different constructor with another <TT>ExecutorService</TT>
45       */
46      public ParallelObservable() {
47          this.loop = PackCst.EXECUTOR_SERVICE ;
48      }
49  
50      public ParallelObservable(ExecutorService execService) {
51          this.loop = execService ;
52      }
53  
54       public void addObserver(ASyncObserver<P> observer){
55          this.list.add(observer);
56      }
57  
58      public void removeObserver(ASyncObserver<P> observer){
59          this.list.remove (observer);
60      }
61  
62      /**
63       * do not need a call to <TT>setChanged</TT>: observers
64       * are immediately notified through different threads
65       *
66       * @param data
67       */
68      public void notifyObservers(P data) {
69          for(ASyncObserver<P> observer : list) {
70              loop.submit(new DoUpdate<P>(observer, data)) ;
71          }
72  
73      }
74  }