Coverage Summary for Class: EventBus (com.google.common.eventbus)
| Class | Method, % | Line, % |
|---|---|---|
| EventBus | 0% (0/12) | 0% (0/31) |
| EventBus$LoggingHandler | 0% (0/5) | 0% (0/12) |
| Total | 0% (0/17) | 0% (0/43) |
1 /* 2 * Copyright (C) 2007 The Guava Authors 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 5 * in compliance with the License. You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software distributed under the License 10 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 11 * or implied. See the License for the specific language governing permissions and limitations under 12 * the License. 13 */ 14 15 package com.google.common.eventbus; 16 17 import static com.google.common.base.Preconditions.checkNotNull; 18 19 import com.google.common.base.MoreObjects; 20 import com.google.common.util.concurrent.MoreExecutors; 21 import java.lang.reflect.Method; 22 import java.util.Iterator; 23 import java.util.Locale; 24 import java.util.concurrent.Executor; 25 import java.util.logging.Level; 26 import java.util.logging.Logger; 27 28 /** 29 * Dispatches events to listeners, and provides ways for listeners to register themselves. 30 * 31 * <h2>Avoid EventBus</h2> 32 * 33 * <p><b>We recommend against using EventBus.</b> It was designed many years ago, and newer 34 * libraries offer better ways to decouple components and react to events. 35 * 36 * <p>To decouple components, we recommend a dependency-injection framework. For Android code, most 37 * apps use <a href="https://dagger.dev">Dagger</a>. For server code, common options include <a 38 * href="https://github.com/google/guice/wiki/Motivation">Guice</a> and <a 39 * href="https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans-introduction">Spring</a>. 40 * Frameworks typically offer a way to register multiple listeners independently and then request 41 * them together as a set (<a href="https://dagger.dev/dev-guide/multibindings">Dagger</a>, <a 42 * href="https://github.com/google/guice/wiki/Multibindings">Guice</a>, <a 43 * href="https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans-autowired-annotation">Spring</a>). 44 * 45 * <p>To react to events, we recommend a reactive-streams framework like <a 46 * href="https://github.com/ReactiveX/RxJava/wiki">RxJava</a> (supplemented with its <a 47 * href="https://github.com/ReactiveX/RxAndroid">RxAndroid</a> extension if you are building for 48 * Android) or <a href="https://projectreactor.io/">Project Reactor</a>. (For the basics of 49 * translating code from using an event bus to using a reactive-streams framework, see these two 50 * guides: <a href="https://blog.jkl.gg/implementing-an-event-bus-with-rxjava-rxbus/">1</a>, <a 51 * href="https://lorentzos.com/rxjava-as-event-bus-the-right-way-10a36bdd49ba">2</a>.) Some usages 52 * of EventBus may be better written using <a 53 * href="https://kotlinlang.org/docs/coroutines-guide.html">Kotlin coroutines</a>, including <a 54 * href="https://kotlinlang.org/docs/flow.html">Flow</a> and <a 55 * href="https://kotlinlang.org/docs/channels.html">Channels</a>. Yet other usages are better served 56 * by individual libraries that provide specialized support for particular use cases. 57 * 58 * <p>Disadvantages of EventBus include: 59 * 60 * <ul> 61 * <li>It makes the cross-references between producer and subscriber harder to find. This can 62 * complicate debugging, lead to unintentional reentrant calls, and force apps to eagerly 63 * initialize all possible subscribers at startup time. 64 * <li>It doesn't offer a way to wait for multiple events before taking action. For example, it 65 * doesn't offer a way to wait for multiple producers to all report that they're "ready," nor 66 * does it offer a way to batch multiple events from a single producer together. 67 * <li>It doesn't support backpressure and other features needed for resilience. 68 * <li>It doesn't provide much control of threading. 69 * <li>It doesn't offer much monitoring. 70 * <li>It doesn't propagate exceptions, so apps don't have a way to react to them. 71 * <li>It doesn't interoperate well with RxJava, coroutines, and other more commonly used 72 * alternatives. 73 * <li>It imposes requirements on the lifecycle of its subscribers. For example, if an event 74 * occurs between when one subscriber is removed and the next subscriber is added, the event 75 * is dropped. 76 * <li>Its performance is suboptimal, especially under Android. 77 * <li>It <a href="https://github.com/google/guava/issues/1431">doesn't support parameterized 78 * types</a>. 79 * <li>With the introduction of lambdas in Java 8, EventBus went from less verbose than listeners 80 * to <a href="https://github.com/google/guava/issues/3311">more verbose</a>. 81 * </ul> 82 * 83 * <h2>EventBus Summary</h2> 84 * 85 * <p>The EventBus allows publish-subscribe-style communication between components without requiring 86 * the components to explicitly register with one another (and thus be aware of each other). It is 87 * designed exclusively to replace traditional Java in-process event distribution using explicit 88 * registration. It is <em>not</em> a general-purpose publish-subscribe system, nor is it intended 89 * for interprocess communication. 90 * 91 * <h2>Receiving Events</h2> 92 * 93 * <p>To receive events, an object should: 94 * 95 * <ol> 96 * <li>Expose a public method, known as the <i>event subscriber</i>, which accepts a single 97 * argument of the type of event desired; 98 * <li>Mark it with a {@link Subscribe} annotation; 99 * <li>Pass itself to an EventBus instance's {@link #register(Object)} method. 100 * </ol> 101 * 102 * <h2>Posting Events</h2> 103 * 104 * <p>To post an event, simply provide the event object to the {@link #post(Object)} method. The 105 * EventBus instance will determine the type of event and route it to all registered listeners. 106 * 107 * <p>Events are routed based on their type — an event will be delivered to any subscriber for 108 * any type to which the event is <em>assignable.</em> This includes implemented interfaces, all 109 * superclasses, and all interfaces implemented by superclasses. 110 * 111 * <p>When {@code post} is called, all registered subscribers for an event are run in sequence, so 112 * subscribers should be reasonably quick. If an event may trigger an extended process (such as a 113 * database load), spawn a thread or queue it for later. (For a convenient way to do this, use an 114 * {@link AsyncEventBus}.) 115 * 116 * <h2>Subscriber Methods</h2> 117 * 118 * <p>Event subscriber methods must accept only one argument: the event. 119 * 120 * <p>Subscribers should not, in general, throw. If they do, the EventBus will catch and log the 121 * exception. This is rarely the right solution for error handling and should not be relied upon; it 122 * is intended solely to help find problems during development. 123 * 124 * <p>The EventBus guarantees that it will not call a subscriber method from multiple threads 125 * simultaneously, unless the method explicitly allows it by bearing the {@link 126 * AllowConcurrentEvents} annotation. If this annotation is not present, subscriber methods need not 127 * worry about being reentrant, unless also called from outside the EventBus. 128 * 129 * <h2>Dead Events</h2> 130 * 131 * <p>If an event is posted, but no registered subscribers can accept it, it is considered "dead." 132 * To give the system a second chance to handle dead events, they are wrapped in an instance of 133 * {@link DeadEvent} and reposted. 134 * 135 * <p>If a subscriber for a supertype of all events (such as Object) is registered, no event will 136 * ever be considered dead, and no DeadEvents will be generated. Accordingly, while DeadEvent 137 * extends {@link Object}, a subscriber registered to receive any Object will never receive a 138 * DeadEvent. 139 * 140 * <p>This class is safe for concurrent use. 141 * 142 * <p>See the Guava User Guide article on <a 143 * href="https://github.com/google/guava/wiki/EventBusExplained">{@code EventBus}</a>. 144 * 145 * @author Cliff Biffle 146 * @since 10.0 147 */ 148 @ElementTypesAreNonnullByDefault 149 public class EventBus { 150 151 private static final Logger logger = Logger.getLogger(EventBus.class.getName()); 152 153 private final String identifier; 154 private final Executor executor; 155 private final SubscriberExceptionHandler exceptionHandler; 156 157 private final SubscriberRegistry subscribers = new SubscriberRegistry(this); 158 private final Dispatcher dispatcher; 159 160 /** Creates a new EventBus named "default". */ 161 public EventBus() { 162 this("default"); 163 } 164 165 /** 166 * Creates a new EventBus with the given {@code identifier}. 167 * 168 * @param identifier a brief name for this bus, for logging purposes. Should be a valid Java 169 * identifier. 170 */ 171 public EventBus(String identifier) { 172 this( 173 identifier, 174 MoreExecutors.directExecutor(), 175 Dispatcher.perThreadDispatchQueue(), 176 LoggingHandler.INSTANCE); 177 } 178 179 /** 180 * Creates a new EventBus with the given {@link SubscriberExceptionHandler}. 181 * 182 * @param exceptionHandler Handler for subscriber exceptions. 183 * @since 16.0 184 */ 185 public EventBus(SubscriberExceptionHandler exceptionHandler) { 186 this( 187 "default", 188 MoreExecutors.directExecutor(), 189 Dispatcher.perThreadDispatchQueue(), 190 exceptionHandler); 191 } 192 193 EventBus( 194 String identifier, 195 Executor executor, 196 Dispatcher dispatcher, 197 SubscriberExceptionHandler exceptionHandler) { 198 this.identifier = checkNotNull(identifier); 199 this.executor = checkNotNull(executor); 200 this.dispatcher = checkNotNull(dispatcher); 201 this.exceptionHandler = checkNotNull(exceptionHandler); 202 } 203 204 /** 205 * Returns the identifier for this event bus. 206 * 207 * @since 19.0 208 */ 209 public final String identifier() { 210 return identifier; 211 } 212 213 /** Returns the default executor this event bus uses for dispatching events to subscribers. */ 214 final Executor executor() { 215 return executor; 216 } 217 218 /** Handles the given exception thrown by a subscriber with the given context. */ 219 void handleSubscriberException(Throwable e, SubscriberExceptionContext context) { 220 checkNotNull(e); 221 checkNotNull(context); 222 try { 223 exceptionHandler.handleException(e, context); 224 } catch (Throwable e2) { 225 // if the handler threw an exception... well, just log it 226 logger.log( 227 Level.SEVERE, 228 String.format(Locale.ROOT, "Exception %s thrown while handling exception: %s", e2, e), 229 e2); 230 } 231 } 232 233 /** 234 * Registers all subscriber methods on {@code object} to receive events. 235 * 236 * @param object object whose subscriber methods should be registered. 237 */ 238 public void register(Object object) { 239 subscribers.register(object); 240 } 241 242 /** 243 * Unregisters all subscriber methods on a registered {@code object}. 244 * 245 * @param object object whose subscriber methods should be unregistered. 246 * @throws IllegalArgumentException if the object was not previously registered. 247 */ 248 public void unregister(Object object) { 249 subscribers.unregister(object); 250 } 251 252 /** 253 * Posts an event to all registered subscribers. This method will return successfully after the 254 * event has been posted to all subscribers, and regardless of any exceptions thrown by 255 * subscribers. 256 * 257 * <p>If no subscribers have been subscribed for {@code event}'s class, and {@code event} is not 258 * already a {@link DeadEvent}, it will be wrapped in a DeadEvent and reposted. 259 * 260 * @param event event to post. 261 */ 262 public void post(Object event) { 263 Iterator<Subscriber> eventSubscribers = subscribers.getSubscribers(event); 264 if (eventSubscribers.hasNext()) { 265 dispatcher.dispatch(event, eventSubscribers); 266 } else if (!(event instanceof DeadEvent)) { 267 // the event had no subscribers and was not itself a DeadEvent 268 post(new DeadEvent(this, event)); 269 } 270 } 271 272 @Override 273 public String toString() { 274 return MoreObjects.toStringHelper(this).addValue(identifier).toString(); 275 } 276 277 /** Simple logging handler for subscriber exceptions. */ 278 static final class LoggingHandler implements SubscriberExceptionHandler { 279 static final LoggingHandler INSTANCE = new LoggingHandler(); 280 281 @Override 282 public void handleException(Throwable exception, SubscriberExceptionContext context) { 283 Logger logger = logger(context); 284 if (logger.isLoggable(Level.SEVERE)) { 285 logger.log(Level.SEVERE, message(context), exception); 286 } 287 } 288 289 private static Logger logger(SubscriberExceptionContext context) { 290 return Logger.getLogger(EventBus.class.getName() + "." + context.getEventBus().identifier()); 291 } 292 293 private static String message(SubscriberExceptionContext context) { 294 Method method = context.getSubscriberMethod(); 295 return "Exception thrown by subscriber method " 296 + method.getName() 297 + '(' 298 + method.getParameterTypes()[0].getName() 299 + ')' 300 + " on subscriber " 301 + context.getSubscriber() 302 + " when dispatching event: " 303 + context.getEvent(); 304 } 305 } 306 }