001    /*
002     * Copyright (C) 2007 The Guava Authors
003     *
004     * Licensed under the Apache License, Version 2.0 (the "License");
005     * you may not use this file except in compliance with the License.
006     * You may obtain a copy of the License at
007     *
008     * http://www.apache.org/licenses/LICENSE-2.0
009     *
010     * Unless required by applicable law or agreed to in writing, software
011     * distributed under the License is distributed on an "AS IS" BASIS,
012     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013     * See the License for the specific language governing permissions and
014     * limitations under the License.
015     */
016    
017    package com.google.common.eventbus;
018    
019    import com.google.common.annotations.Beta;
020    import com.google.common.annotations.VisibleForTesting;
021    import com.google.common.base.Supplier;
022    import com.google.common.base.Throwables;
023    import com.google.common.cache.CacheBuilder;
024    import com.google.common.cache.CacheLoader;
025    import com.google.common.cache.LoadingCache;
026    import com.google.common.collect.Multimap;
027    import com.google.common.collect.Multimaps;
028    import com.google.common.collect.SetMultimap;
029    import com.google.common.reflect.TypeToken;
030    
031    import java.lang.reflect.InvocationTargetException;
032    import java.util.Collection;
033    import java.util.Map.Entry;
034    import java.util.Set;
035    import java.util.concurrent.ConcurrentHashMap;
036    import java.util.concurrent.ConcurrentLinkedQueue;
037    import java.util.concurrent.CopyOnWriteArraySet;
038    import java.util.concurrent.ExecutionException;
039    import java.util.logging.Level;
040    import java.util.logging.Logger;
041    
042    /**
043     * Dispatches events to listeners, and provides ways for listeners to register
044     * themselves.
045     *
046     * <p>The EventBus allows publish-subscribe-style communication between
047     * components without requiring the components to explicitly register with one
048     * another (and thus be aware of each other).  It is designed exclusively to
049     * replace traditional Java in-process event distribution using explicit
050     * registration. It is <em>not</em> a general-purpose publish-subscribe system,
051     * nor is it intended for interprocess communication.
052     *
053     * <h2>Receiving Events</h2>
054     * To receive events, an object should:<ol>
055     * <li>Expose a public method, known as the <i>event handler</i>, which accepts
056     *     a single argument of the type of event desired;</li>
057     * <li>Mark it with a {@link Subscribe} annotation;</li>
058     * <li>Pass itself to an EventBus instance's {@link #register(Object)} method.
059     *     </li>
060     * </ol>
061     *
062     * <h2>Posting Events</h2>
063     * To post an event, simply provide the event object to the
064     * {@link #post(Object)} method.  The EventBus instance will determine the type
065     * of event and route it to all registered listeners.
066     *
067     * <p>Events are routed based on their type &mdash; an event will be delivered
068     * to any handler for any type to which the event is <em>assignable.</em>  This
069     * includes implemented interfaces, all superclasses, and all interfaces
070     * implemented by superclasses.
071     *
072     * <p>When {@code post} is called, all registered handlers for an event are run
073     * in sequence, so handlers should be reasonably quick.  If an event may trigger
074     * an extended process (such as a database load), spawn a thread or queue it for
075     * later.  (For a convenient way to do this, use an {@link AsyncEventBus}.)
076     *
077     * <h2>Handler Methods</h2>
078     * Event handler methods must accept only one argument: the event.
079     *
080     * <p>Handlers should not, in general, throw.  If they do, the EventBus will
081     * catch and log the exception.  This is rarely the right solution for error
082     * handling and should not be relied upon; it is intended solely to help find
083     * problems during development.
084     *
085     * <p>The EventBus guarantees that it will not call a handler method from
086     * multiple threads simultaneously, unless the method explicitly allows it by
087     * bearing the {@link AllowConcurrentEvents} annotation.  If this annotation is
088     * not present, handler methods need not worry about being reentrant, unless
089     * also called from outside the EventBus.
090     *
091     * <h2>Dead Events</h2>
092     * If an event is posted, but no registered handlers can accept it, it is
093     * considered "dead."  To give the system a second chance to handle dead events,
094     * they are wrapped in an instance of {@link DeadEvent} and reposted.
095     *
096     * <p>If a handler for a supertype of all events (such as Object) is registered,
097     * no event will ever be considered dead, and no DeadEvents will be generated.
098     * Accordingly, while DeadEvent extends {@link Object}, a handler registered to
099     * receive any Object will never receive a DeadEvent.
100     *
101     * <p>This class is safe for concurrent use.
102     * 
103     * <p>See the Guava User Guide article on <a href=
104     * "http://code.google.com/p/guava-libraries/wiki/EventBusExplained">
105     * {@code EventBus}</a>.
106     *
107     * @author Cliff Biffle
108     * @since 10.0
109     */
110    @Beta
111    public class EventBus {
112    
113      /**
114       * All registered event handlers, indexed by event type.
115       */
116      private final SetMultimap<Class<?>, EventHandler> handlersByType =
117          Multimaps.newSetMultimap(new ConcurrentHashMap<Class<?>, Collection<EventHandler>>(),
118              new Supplier<Set<EventHandler>>() {
119                public Set<EventHandler> get() {
120                  return newHandlerSet();
121                }
122              });
123    
124      /**
125       * Logger for event dispatch failures.  Named by the fully-qualified name of
126       * this class, followed by the identifier provided at construction.
127       */
128      private final Logger logger;
129    
130      /**
131       * Strategy for finding handler methods in registered objects.  Currently,
132       * only the {@link AnnotatedHandlerFinder} is supported, but this is
133       * encapsulated for future expansion.
134       */
135      private final HandlerFindingStrategy finder = new AnnotatedHandlerFinder();
136    
137      /** queues of events for the current thread to dispatch */
138      private final ThreadLocal<ConcurrentLinkedQueue<EventWithHandler>>
139          eventsToDispatch =
140          new ThreadLocal<ConcurrentLinkedQueue<EventWithHandler>>() {
141        
142        @Override
143        protected ConcurrentLinkedQueue<EventWithHandler> initialValue() {
144          return new ConcurrentLinkedQueue<EventWithHandler>();
145        }
146      };
147    
148      /** true if the current thread is currently dispatching an event */
149      private final ThreadLocal<Boolean> isDispatching =
150          new ThreadLocal<Boolean>() {
151        
152        @Override
153        protected Boolean initialValue() {
154          return false;
155        }
156      };
157    
158      /**
159       * A thread-safe cache for flattenHierarchy(). The Class class is immutable.
160       */
161      private final LoadingCache<Class<?>, Set<Class<?>>> flattenHierarchyCache =
162          CacheBuilder.newBuilder()
163              .weakKeys()
164              .build(new CacheLoader<Class<?>, Set<Class<?>>>() {
165                @Override
166                @SuppressWarnings({"unchecked", "rawtypes"}) // safe cast
167                
168                public Set<Class<?>> load(Class<?> concreteClass) throws Exception {
169                  return (Set) TypeToken.of(concreteClass).getTypes().rawTypes();
170                }
171              });
172    
173      /**
174       * Creates a new EventBus named "default".
175       */
176      public EventBus() {
177        this("default");
178      }
179    
180      /**
181       * Creates a new EventBus with the given {@code identifier}.
182       *
183       * @param identifier  a brief name for this bus, for logging purposes.  Should
184       *                    be a valid Java identifier.
185       */
186      public EventBus(String identifier) {
187        logger = Logger.getLogger(EventBus.class.getName() + "." + identifier);
188      }
189    
190      /**
191       * Registers all handler methods on {@code object} to receive events.
192       * Handler methods are selected and classified using this EventBus's
193       * {@link HandlerFindingStrategy}; the default strategy is the
194       * {@link AnnotatedHandlerFinder}.
195       *
196       * @param object  object whose handler methods should be registered.
197       */
198      public void register(Object object) {
199        handlersByType.putAll(finder.findAllHandlers(object));
200      }
201    
202      /**
203       * Unregisters all handler methods on a registered {@code object}.
204       *
205       * @param object  object whose handler methods should be unregistered.
206       * @throws IllegalArgumentException if the object was not previously registered.
207       */
208      public void unregister(Object object) {
209        Multimap<Class<?>, EventHandler> methodsInListener = finder.findAllHandlers(object);
210        for (Entry<Class<?>, Collection<EventHandler>> entry : methodsInListener.asMap().entrySet()) {
211          Set<EventHandler> currentHandlers = getHandlersForEventType(entry.getKey());
212          Collection<EventHandler> eventMethodsInListener = entry.getValue();
213          
214          if (currentHandlers == null || !currentHandlers.containsAll(entry.getValue())) {
215            throw new IllegalArgumentException(
216                "missing event handler for an annotated method. Is " + object + " registered?");
217          }
218          currentHandlers.removeAll(eventMethodsInListener);
219        }
220      }
221    
222      /**
223       * Posts an event to all registered handlers.  This method will return
224       * successfully after the event has been posted to all handlers, and
225       * regardless of any exceptions thrown by handlers.
226       *
227       * <p>If no handlers have been subscribed for {@code event}'s class, and
228       * {@code event} is not already a {@link DeadEvent}, it will be wrapped in a
229       * DeadEvent and reposted.
230       *
231       * @param event  event to post.
232       */
233      @SuppressWarnings("deprecation") // only deprecated for external subclasses
234      public void post(Object event) {
235        Set<Class<?>> dispatchTypes = flattenHierarchy(event.getClass());
236    
237        boolean dispatched = false;
238        for (Class<?> eventType : dispatchTypes) {
239          Set<EventHandler> wrappers = getHandlersForEventType(eventType);
240    
241          if (wrappers != null && !wrappers.isEmpty()) {
242            dispatched = true;
243            for (EventHandler wrapper : wrappers) {
244              enqueueEvent(event, wrapper);
245            }
246          }
247        }
248    
249        if (!dispatched && !(event instanceof DeadEvent)) {
250          post(new DeadEvent(this, event));
251        }
252    
253        dispatchQueuedEvents();
254      }
255    
256      /**
257       * Queue the {@code event} for dispatch during
258       * {@link #dispatchQueuedEvents()}. Events are queued in-order of occurrence
259       * so they can be dispatched in the same order.
260       */
261      void enqueueEvent(Object event, EventHandler handler) {
262        eventsToDispatch.get().offer(new EventWithHandler(event, handler));
263      }
264    
265      /**
266       * Drain the queue of events to be dispatched. As the queue is being drained,
267       * new events may be posted to the end of the queue.
268       *
269       * @deprecated This method should not be overridden outside of the eventbus package. It is
270       *     scheduled for removal in Guava 14.0.
271       */
272      @Deprecated
273      protected void dispatchQueuedEvents() {
274        // don't dispatch if we're already dispatching, that would allow reentrancy
275        // and out-of-order events. Instead, leave the events to be dispatched
276        // after the in-progress dispatch is complete.
277        if (isDispatching.get()) {
278          return;
279        }
280    
281        isDispatching.set(true);
282        try {
283          while (true) {
284            EventWithHandler eventWithHandler = eventsToDispatch.get().poll();
285            if (eventWithHandler == null) {
286              break;
287            }
288    
289            dispatch(eventWithHandler.event, eventWithHandler.handler);
290          }
291        } finally {
292          isDispatching.set(false);
293        }
294      }
295    
296      /**
297       * Dispatches {@code event} to the handler in {@code wrapper}.  This method
298       * is an appropriate override point for subclasses that wish to make
299       * event delivery asynchronous.
300       *
301       * @param event  event to dispatch.
302       * @param wrapper  wrapper that will call the handler.
303       */
304      void dispatch(Object event, EventHandler wrapper) {
305        try {
306          wrapper.handleEvent(event);
307        } catch (InvocationTargetException e) {
308          logger.log(Level.SEVERE,
309              "Could not dispatch event: " + event + " to handler " + wrapper, e);
310        }
311      }
312    
313      /**
314       * Retrieves a mutable set of the currently registered handlers for
315       * {@code type}.  If no handlers are currently registered for {@code type},
316       * this method may either return {@code null} or an empty set.
317       *
318       * @param type  type of handlers to retrieve.
319       * @return currently registered handlers, or {@code null}.
320       */
321      Set<EventHandler> getHandlersForEventType(Class<?> type) {
322        return handlersByType.get(type);
323      }
324    
325      /**
326       * Creates a new Set for insertion into the handler map.  This is provided
327       * as an override point for subclasses. The returned set should support
328       * concurrent access.
329       *
330       * @return a new, mutable set for handlers.
331       */
332      Set<EventHandler> newHandlerSet() {
333        return new CopyOnWriteArraySet<EventHandler>();
334      }
335    
336      /**
337       * Flattens a class's type hierarchy into a set of Class objects.  The set
338       * will include all superclasses (transitively), and all interfaces
339       * implemented by these superclasses.
340       *
341       * @param concreteClass  class whose type hierarchy will be retrieved.
342       * @return {@code clazz}'s complete type hierarchy, flattened and uniqued.
343       */
344      @VisibleForTesting
345      Set<Class<?>> flattenHierarchy(Class<?> concreteClass) {
346        try {
347          return flattenHierarchyCache.get(concreteClass);
348        } catch (ExecutionException e) {
349          throw Throwables.propagate(e.getCause());
350        }
351      }
352    
353      /** simple struct representing an event and it's handler */
354      static class EventWithHandler {
355        final Object event;
356        final EventHandler handler;
357        public EventWithHandler(Object event, EventHandler handler) {
358          this.event = event;
359          this.handler = handler;
360        }
361      }
362    }