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
017package com.google.common.eventbus;
018
019import com.google.common.annotations.Beta;
020import com.google.common.annotations.VisibleForTesting;
021import com.google.common.base.Supplier;
022import com.google.common.base.Throwables;
023import com.google.common.cache.CacheBuilder;
024import com.google.common.cache.CacheLoader;
025import com.google.common.cache.LoadingCache;
026import com.google.common.collect.Multimap;
027import com.google.common.collect.Multimaps;
028import com.google.common.collect.SetMultimap;
029import com.google.common.reflect.TypeToken;
030
031import java.lang.reflect.InvocationTargetException;
032import java.util.Collection;
033import java.util.Map.Entry;
034import java.util.Set;
035import java.util.concurrent.ConcurrentHashMap;
036import java.util.concurrent.ConcurrentLinkedQueue;
037import java.util.concurrent.CopyOnWriteArraySet;
038import java.util.concurrent.ExecutionException;
039import java.util.logging.Level;
040import 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
111public 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            @Override
120            public Set<EventHandler> get() {
121              return newHandlerSet();
122            }
123          });
124
125  /**
126   * Logger for event dispatch failures.  Named by the fully-qualified name of
127   * this class, followed by the identifier provided at construction.
128   */
129  private final Logger logger;
130
131  /**
132   * Strategy for finding handler methods in registered objects.  Currently,
133   * only the {@link AnnotatedHandlerFinder} is supported, but this is
134   * encapsulated for future expansion.
135   */
136  private final HandlerFindingStrategy finder = new AnnotatedHandlerFinder();
137
138  /** queues of events for the current thread to dispatch */
139  private final ThreadLocal<ConcurrentLinkedQueue<EventWithHandler>>
140      eventsToDispatch =
141      new ThreadLocal<ConcurrentLinkedQueue<EventWithHandler>>() {
142    @Override protected ConcurrentLinkedQueue<EventWithHandler> initialValue() {
143      return new ConcurrentLinkedQueue<EventWithHandler>();
144    }
145  };
146
147  /** true if the current thread is currently dispatching an event */
148  private final ThreadLocal<Boolean> isDispatching =
149      new ThreadLocal<Boolean>() {
150    @Override protected Boolean initialValue() {
151      return false;
152    }
153  };
154
155  /**
156   * A thread-safe cache for flattenHierarchy(). The Class class is immutable.
157   */
158  private final LoadingCache<Class<?>, Set<Class<?>>> flattenHierarchyCache =
159      CacheBuilder.newBuilder()
160          .weakKeys()
161          .build(new CacheLoader<Class<?>, Set<Class<?>>>() {
162            @SuppressWarnings({"unchecked", "rawtypes"}) // safe cast
163            @Override
164            public Set<Class<?>> load(Class<?> concreteClass) throws Exception {
165              return (Set) TypeToken.of(concreteClass).getTypes().rawTypes();
166            }
167          });
168
169  /**
170   * Creates a new EventBus named "default".
171   */
172  public EventBus() {
173    this("default");
174  }
175
176  /**
177   * Creates a new EventBus with the given {@code identifier}.
178   *
179   * @param identifier  a brief name for this bus, for logging purposes.  Should
180   *                    be a valid Java identifier.
181   */
182  public EventBus(String identifier) {
183    logger = Logger.getLogger(EventBus.class.getName() + "." + identifier);
184  }
185
186  /**
187   * Registers all handler methods on {@code object} to receive events.
188   * Handler methods are selected and classified using this EventBus's
189   * {@link HandlerFindingStrategy}; the default strategy is the
190   * {@link AnnotatedHandlerFinder}.
191   *
192   * @param object  object whose handler methods should be registered.
193   */
194  public void register(Object object) {
195    handlersByType.putAll(finder.findAllHandlers(object));
196  }
197
198  /**
199   * Unregisters all handler methods on a registered {@code object}.
200   *
201   * @param object  object whose handler methods should be unregistered.
202   * @throws IllegalArgumentException if the object was not previously registered.
203   */
204  public void unregister(Object object) {
205    Multimap<Class<?>, EventHandler> methodsInListener = finder.findAllHandlers(object);
206    for (Entry<Class<?>, Collection<EventHandler>> entry : methodsInListener.asMap().entrySet()) {
207      Set<EventHandler> currentHandlers = getHandlersForEventType(entry.getKey());
208      Collection<EventHandler> eventMethodsInListener = entry.getValue();
209      
210      if (currentHandlers == null || !currentHandlers.containsAll(entry.getValue())) {
211        throw new IllegalArgumentException(
212            "missing event handler for an annotated method. Is " + object + " registered?");
213      }
214      currentHandlers.removeAll(eventMethodsInListener);
215    }
216  }
217
218  /**
219   * Posts an event to all registered handlers.  This method will return
220   * successfully after the event has been posted to all handlers, and
221   * regardless of any exceptions thrown by handlers.
222   *
223   * <p>If no handlers have been subscribed for {@code event}'s class, and
224   * {@code event} is not already a {@link DeadEvent}, it will be wrapped in a
225   * DeadEvent and reposted.
226   *
227   * @param event  event to post.
228   */
229  @SuppressWarnings("deprecation") // only deprecated for external subclasses
230  public void post(Object event) {
231    Set<Class<?>> dispatchTypes = flattenHierarchy(event.getClass());
232
233    boolean dispatched = false;
234    for (Class<?> eventType : dispatchTypes) {
235      Set<EventHandler> wrappers = getHandlersForEventType(eventType);
236
237      if (wrappers != null && !wrappers.isEmpty()) {
238        dispatched = true;
239        for (EventHandler wrapper : wrappers) {
240          enqueueEvent(event, wrapper);
241        }
242      }
243    }
244
245    if (!dispatched && !(event instanceof DeadEvent)) {
246      post(new DeadEvent(this, event));
247    }
248
249    dispatchQueuedEvents();
250  }
251
252  /**
253   * Queue the {@code event} for dispatch during
254   * {@link #dispatchQueuedEvents()}. Events are queued in-order of occurrence
255   * so they can be dispatched in the same order.
256   */
257  void enqueueEvent(Object event, EventHandler handler) {
258    eventsToDispatch.get().offer(new EventWithHandler(event, handler));
259  }
260
261  /**
262   * Drain the queue of events to be dispatched. As the queue is being drained,
263   * new events may be posted to the end of the queue.
264   *
265   * @deprecated This method should not be overridden outside of the eventbus package. It is
266   *     scheduled for removal in Guava 14.0.
267   */
268  @Deprecated
269  protected void dispatchQueuedEvents() {
270    // don't dispatch if we're already dispatching, that would allow reentrancy
271    // and out-of-order events. Instead, leave the events to be dispatched
272    // after the in-progress dispatch is complete.
273    if (isDispatching.get()) {
274      return;
275    }
276
277    isDispatching.set(true);
278    try {
279      while (true) {
280        EventWithHandler eventWithHandler = eventsToDispatch.get().poll();
281        if (eventWithHandler == null) {
282          break;
283        }
284
285        dispatch(eventWithHandler.event, eventWithHandler.handler);
286      }
287    } finally {
288      isDispatching.set(false);
289    }
290  }
291
292  /**
293   * Dispatches {@code event} to the handler in {@code wrapper}.  This method
294   * is an appropriate override point for subclasses that wish to make
295   * event delivery asynchronous.
296   *
297   * @param event  event to dispatch.
298   * @param wrapper  wrapper that will call the handler.
299   */
300  void dispatch(Object event, EventHandler wrapper) {
301    try {
302      wrapper.handleEvent(event);
303    } catch (InvocationTargetException e) {
304      logger.log(Level.SEVERE,
305          "Could not dispatch event: " + event + " to handler " + wrapper, e);
306    }
307  }
308
309  /**
310   * Retrieves a mutable set of the currently registered handlers for
311   * {@code type}.  If no handlers are currently registered for {@code type},
312   * this method may either return {@code null} or an empty set.
313   *
314   * @param type  type of handlers to retrieve.
315   * @return currently registered handlers, or {@code null}.
316   */
317  Set<EventHandler> getHandlersForEventType(Class<?> type) {
318    return handlersByType.get(type);
319  }
320
321  /**
322   * Creates a new Set for insertion into the handler map.  This is provided
323   * as an override point for subclasses. The returned set should support
324   * concurrent access.
325   *
326   * @return a new, mutable set for handlers.
327   */
328  Set<EventHandler> newHandlerSet() {
329    return new CopyOnWriteArraySet<EventHandler>();
330  }
331
332  /**
333   * Flattens a class's type hierarchy into a set of Class objects.  The set
334   * will include all superclasses (transitively), and all interfaces
335   * implemented by these superclasses.
336   *
337   * @param concreteClass  class whose type hierarchy will be retrieved.
338   * @return {@code clazz}'s complete type hierarchy, flattened and uniqued.
339   */
340  @VisibleForTesting
341  Set<Class<?>> flattenHierarchy(Class<?> concreteClass) {
342    try {
343      return flattenHierarchyCache.get(concreteClass);
344    } catch (ExecutionException e) {
345      throw Throwables.propagate(e.getCause());
346    }
347  }
348
349  /** simple struct representing an event and it's handler */
350  static class EventWithHandler {
351    final Object event;
352    final EventHandler handler;
353    public EventWithHandler(Object event, EventHandler handler) {
354      this.event = event;
355      this.handler = handler;
356    }
357  }
358}