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