001/*
002 * Copyright (C) 2007 The Guava Authors
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
005 * in compliance with the License. You may obtain a copy of the License at
006 *
007 * http://www.apache.org/licenses/LICENSE-2.0
008 *
009 * Unless required by applicable law or agreed to in writing, software distributed under the License
010 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
011 * or implied. See the License for the specific language governing permissions and limitations under
012 * the License.
013 */
014
015package com.google.common.eventbus;
016
017import static com.google.common.base.Preconditions.checkNotNull;
018
019import com.google.common.base.MoreObjects;
020import com.google.common.util.concurrent.MoreExecutors;
021import java.lang.reflect.Method;
022import java.util.Iterator;
023import java.util.Locale;
024import java.util.concurrent.Executor;
025import java.util.logging.Level;
026import java.util.logging.Logger;
027
028/**
029 * Dispatches events to listeners, and provides ways for listeners to register themselves.
030
031 *
032 * <h2>Avoid EventBus</h2>
033 *
034 * <p><b>We recommend against using EventBus.</b> It was designed many years ago, and newer
035 * libraries offer better ways to decouple components and react to events.
036 *
037 * <p>To decouple components, we recommend a dependency-injection framework. For Android code, most
038 * apps use <a href="https://dagger.dev">Dagger</a>. For server code, common options include <a
039 * href="https://github.com/google/guice/wiki/Motivation">Guice</a> and <a
040 * href="https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans-introduction">Spring</a>.
041 * Frameworks typically offer a way to register multiple listeners independently and then request
042 * them together as a set (<a href="https://dagger.dev/dev-guide/multibindings">Dagger</a>, <a
043 * href="https://github.com/google/guice/wiki/Multibindings">Guice</a>, <a
044 * href="https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans-autowired-annotation">Spring</a>).
045 *
046 * <p>To react to events, we recommend a reactive-streams framework like <a
047 * href="https://github.com/ReactiveX/RxJava/wiki">RxJava</a> (supplemented with its <a
048 * href="https://github.com/ReactiveX/RxAndroid">RxAndroid</a> extension if you are building for
049 * Android) or <a href="https://projectreactor.io/">Project Reactor</a>. (For the basics of
050 * translating code from using an event bus to using a reactive-streams framework, see these two
051 * guides: <a href="https://blog.jkl.gg/implementing-an-event-bus-with-rxjava-rxbus/">1</a>, <a
052 * href="https://lorentzos.com/rxjava-as-event-bus-the-right-way-10a36bdd49ba">2</a>.) Some usages
053 * of EventBus may be better written using <a
054 * href="https://kotlinlang.org/docs/coroutines-guide.html">Kotlin coroutines</a>, including <a
055 * href="https://kotlinlang.org/docs/flow.html">Flow</a> and <a
056 * href="https://kotlinlang.org/docs/channels.html">Channels</a>. Yet other usages are better served
057 * by individual libraries that provide specialized support for particular use cases.
058 *
059 * <p>Disadvantages of EventBus include:
060 *
061 * <ul>
062 *   <li>It makes the cross-references between producer and subscriber harder to find. This can
063 *       complicate debugging, lead to unintentional reentrant calls, and force apps to eagerly
064 *       initialize all possible subscribers at startup time.
065 *   <li>It uses reflection in ways that break when code is processed by optimizers/minimizers like
066 *       <a href="https://developer.android.com/studio/build/shrink-code">R8 and Proguard</a>.
067 *   <li>It doesn't offer a way to wait for multiple events before taking action. For example, it
068 *       doesn't offer a way to wait for multiple producers to all report that they're "ready," nor
069 *       does it offer a way to batch multiple events from a single producer together.
070 *   <li>It doesn't support backpressure and other features needed for resilience.
071 *   <li>It doesn't provide much control of threading.
072 *   <li>It doesn't offer much monitoring.
073 *   <li>It doesn't propagate exceptions, so apps don't have a way to react to them.
074 *   <li>It doesn't interoperate well with RxJava, coroutines, and other more commonly used
075 *       alternatives.
076 *   <li>It imposes requirements on the lifecycle of its subscribers. For example, if an event
077 *       occurs between when one subscriber is removed and the next subscriber is added, the event
078 *       is dropped.
079 *   <li>Its performance is suboptimal, especially under Android.
080 *   <li>It <a href="https://github.com/google/guava/issues/1431">doesn't support parameterized
081 *       types</a>.
082 *   <li>With the introduction of lambdas in Java 8, EventBus went from less verbose than listeners
083 *       to <a href="https://github.com/google/guava/issues/3311">more verbose</a>.
084 * </ul>
085 *
086
087 *
088 * <h2>EventBus Summary</h2>
089 *
090 * <p>The EventBus allows publish-subscribe-style communication between components without requiring
091 * the components to explicitly register with one another (and thus be aware of each other). It is
092 * designed exclusively to replace traditional Java in-process event distribution using explicit
093 * registration. It is <em>not</em> a general-purpose publish-subscribe system, nor is it intended
094 * for interprocess communication.
095 *
096 * <h2>Receiving Events</h2>
097 *
098 * <p>To receive events, an object should:
099 *
100 * <ol>
101 *   <li>Expose a public method, known as the <i>event subscriber</i>, which accepts a single
102 *       argument of the type of event desired;
103 *   <li>Mark it with a {@link Subscribe} annotation;
104 *   <li>Pass itself to an EventBus instance's {@link #register(Object)} method.
105 * </ol>
106 *
107 * <h2>Posting Events</h2>
108 *
109 * <p>To post an event, simply provide the event object to the {@link #post(Object)} method. The
110 * EventBus instance will determine the type of event and route it to all registered listeners.
111 *
112 * <p>Events are routed based on their type &mdash; an event will be delivered to any subscriber for
113 * any type to which the event is <em>assignable.</em> This includes implemented interfaces, all
114 * superclasses, and all interfaces implemented by superclasses.
115 *
116 * <p>When {@code post} is called, all registered subscribers for an event are run in sequence, so
117 * subscribers should be reasonably quick. If an event may trigger an extended process (such as a
118 * database load), spawn a thread or queue it for later. (For a convenient way to do this, use an
119 * {@link AsyncEventBus}.)
120 *
121 * <h2>Subscriber Methods</h2>
122 *
123 * <p>Event subscriber methods must accept only one argument: the event.
124 *
125 * <p>Subscribers should not, in general, throw. If they do, the EventBus will catch and log the
126 * exception. This is rarely the right solution for error handling and should not be relied upon; it
127 * is intended solely to help find problems during development.
128 *
129 * <p>The EventBus guarantees that it will not call a subscriber method from multiple threads
130 * simultaneously, unless the method explicitly allows it by bearing the {@link
131 * AllowConcurrentEvents} annotation. If this annotation is not present, subscriber methods need not
132 * worry about being reentrant, unless also called from outside the EventBus.
133 *
134 * <h2>Dead Events</h2>
135 *
136 * <p>If an event is posted, but no registered subscribers can accept it, it is considered "dead."
137 * To give the system a second chance to handle dead events, they are wrapped in an instance of
138 * {@link DeadEvent} and reposted.
139 *
140 * <p>If a subscriber for a supertype of all events (such as Object) is registered, no event will
141 * ever be considered dead, and no DeadEvents will be generated. Accordingly, while DeadEvent
142 * extends {@link Object}, a subscriber registered to receive any Object will never receive a
143 * DeadEvent.
144 *
145 * <p>This class is safe for concurrent use.
146 *
147 * <p>See the Guava User Guide article on <a
148 * href="https://github.com/google/guava/wiki/EventBusExplained">{@code EventBus}</a>.
149 *
150 * @author Cliff Biffle
151 * @since 10.0
152 */
153@ElementTypesAreNonnullByDefault
154public class EventBus {
155
156  private static final Logger logger = Logger.getLogger(EventBus.class.getName());
157
158  private final String identifier;
159  private final Executor executor;
160  private final SubscriberExceptionHandler exceptionHandler;
161
162  private final SubscriberRegistry subscribers = new SubscriberRegistry(this);
163  private final Dispatcher dispatcher;
164
165  /** Creates a new EventBus named "default". */
166  public EventBus() {
167    this("default");
168  }
169
170  /**
171   * Creates a new EventBus with the given {@code identifier}.
172   *
173   * @param identifier a brief name for this bus, for logging purposes. Should be a valid Java
174   *     identifier.
175   */
176  public EventBus(String identifier) {
177    this(
178        identifier,
179        MoreExecutors.directExecutor(),
180        Dispatcher.perThreadDispatchQueue(),
181        LoggingHandler.INSTANCE);
182  }
183
184  /**
185   * Creates a new EventBus with the given {@link SubscriberExceptionHandler}.
186   *
187   * @param exceptionHandler Handler for subscriber exceptions.
188   * @since 16.0
189   */
190  public EventBus(SubscriberExceptionHandler exceptionHandler) {
191    this(
192        "default",
193        MoreExecutors.directExecutor(),
194        Dispatcher.perThreadDispatchQueue(),
195        exceptionHandler);
196  }
197
198  EventBus(
199      String identifier,
200      Executor executor,
201      Dispatcher dispatcher,
202      SubscriberExceptionHandler exceptionHandler) {
203    this.identifier = checkNotNull(identifier);
204    this.executor = checkNotNull(executor);
205    this.dispatcher = checkNotNull(dispatcher);
206    this.exceptionHandler = checkNotNull(exceptionHandler);
207  }
208
209  /**
210   * Returns the identifier for this event bus.
211   *
212   * @since 19.0
213   */
214  public final String identifier() {
215    return identifier;
216  }
217
218  /** Returns the default executor this event bus uses for dispatching events to subscribers. */
219  final Executor executor() {
220    return executor;
221  }
222
223  /** Handles the given exception thrown by a subscriber with the given context. */
224  void handleSubscriberException(Throwable e, SubscriberExceptionContext context) {
225    checkNotNull(e);
226    checkNotNull(context);
227    try {
228      exceptionHandler.handleException(e, context);
229    } catch (Throwable e2) {
230      // if the handler threw an exception... well, just log it
231      logger.log(
232          Level.SEVERE,
233          String.format(Locale.ROOT, "Exception %s thrown while handling exception: %s", e2, e),
234          e2);
235    }
236  }
237
238  /**
239   * Registers all subscriber methods on {@code object} to receive events.
240   *
241   * @param object object whose subscriber methods should be registered.
242   */
243  public void register(Object object) {
244    subscribers.register(object);
245  }
246
247  /**
248   * Unregisters all subscriber methods on a registered {@code object}.
249   *
250   * @param object object whose subscriber methods should be unregistered.
251   * @throws IllegalArgumentException if the object was not previously registered.
252   */
253  public void unregister(Object object) {
254    subscribers.unregister(object);
255  }
256
257  /**
258   * Posts an event to all registered subscribers. This method will return successfully after the
259   * event has been posted to all subscribers, and regardless of any exceptions thrown by
260   * subscribers.
261   *
262   * <p>If no subscribers have been subscribed for {@code event}'s class, and {@code event} is not
263   * already a {@link DeadEvent}, it will be wrapped in a DeadEvent and reposted.
264   *
265   * @param event event to post.
266   */
267  public void post(Object event) {
268    Iterator<Subscriber> eventSubscribers = subscribers.getSubscribers(event);
269    if (eventSubscribers.hasNext()) {
270      dispatcher.dispatch(event, eventSubscribers);
271    } else if (!(event instanceof DeadEvent)) {
272      // the event had no subscribers and was not itself a DeadEvent
273      post(new DeadEvent(this, event));
274    }
275  }
276
277  @Override
278  public String toString() {
279    return MoreObjects.toStringHelper(this).addValue(identifier).toString();
280  }
281
282  /** Simple logging handler for subscriber exceptions. */
283  static final class LoggingHandler implements SubscriberExceptionHandler {
284    static final LoggingHandler INSTANCE = new LoggingHandler();
285
286    @Override
287    public void handleException(Throwable exception, SubscriberExceptionContext context) {
288      Logger logger = logger(context);
289      if (logger.isLoggable(Level.SEVERE)) {
290        logger.log(Level.SEVERE, message(context), exception);
291      }
292    }
293
294    private static Logger logger(SubscriberExceptionContext context) {
295      return Logger.getLogger(EventBus.class.getName() + "." + context.getEventBus().identifier());
296    }
297
298    private static String message(SubscriberExceptionContext context) {
299      Method method = context.getSubscriberMethod();
300      return "Exception thrown by subscriber method "
301          + method.getName()
302          + '('
303          + method.getParameterTypes()[0].getName()
304          + ')'
305          + " on subscriber "
306          + context.getSubscriber()
307          + " when dispatching event: "
308          + context.getEvent();
309    }
310  }
311}