add EventBus
This commit is contained in:
@@ -0,0 +1,5 @@
|
||||
package p.studio.utilities.events;
|
||||
|
||||
public interface EventSubscription {
|
||||
void unsubscribe();
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
package p.studio.utilities.events;
|
||||
|
||||
public interface SimpleEvent {
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package p.studio.utilities.events;
|
||||
|
||||
import java.util.Objects;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.ConcurrentMap;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
public final class TypedEventBus {
|
||||
private final AtomicLong nextSubscriptionId = new AtomicLong(1L);
|
||||
private final ConcurrentMap<Class<?>, ConcurrentMap<Long, Consumer<Object>>> subscriptionsByType =
|
||||
new ConcurrentHashMap<>();
|
||||
|
||||
public <T extends SimpleEvent> EventSubscription subscribe(Class<T> eventType, Consumer<? super T> consumer) {
|
||||
Objects.requireNonNull(eventType, "eventType");
|
||||
Objects.requireNonNull(consumer, "consumer");
|
||||
|
||||
final long subscriptionId = nextSubscriptionId.getAndIncrement();
|
||||
final Consumer<Object> erasedConsumer = event -> consumer.accept(eventType.cast(event));
|
||||
final ConcurrentMap<Long, Consumer<Object>> subscriptions =
|
||||
subscriptionsByType.computeIfAbsent(eventType, ignored -> new ConcurrentHashMap<>());
|
||||
subscriptions.put(subscriptionId, erasedConsumer);
|
||||
|
||||
final AtomicBoolean active = new AtomicBoolean(true);
|
||||
return () -> {
|
||||
if (!active.compareAndSet(true, false)) {
|
||||
return;
|
||||
}
|
||||
|
||||
final ConcurrentMap<Long, Consumer<Object>> currentSubscriptions = subscriptionsByType.get(eventType);
|
||||
if (currentSubscriptions == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
currentSubscriptions.remove(subscriptionId);
|
||||
if (currentSubscriptions.isEmpty()) {
|
||||
subscriptionsByType.remove(eventType, currentSubscriptions);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
public void publish(Object event) {
|
||||
Objects.requireNonNull(event, "event");
|
||||
|
||||
final ConcurrentMap<Long, Consumer<Object>> subscriptions = subscriptionsByType.get(event.getClass());
|
||||
if (subscriptions == null || subscriptions.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
for (Consumer<Object> consumer : subscriptions.values()) {
|
||||
consumer.accept(event);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
package p.studio.utilities.events;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
final class TypedEventBusTest {
|
||||
@Test
|
||||
void publishesTypedEventsToSubscribers() {
|
||||
final TypedEventBus bus = new TypedEventBus();
|
||||
final List<String> received = new CopyOnWriteArrayList<>();
|
||||
|
||||
bus.subscribe(TestEvent.class, event -> received.add(event.value()));
|
||||
bus.publish(new TestEvent("hello"));
|
||||
|
||||
assertEquals(List.of("hello"), received);
|
||||
}
|
||||
|
||||
@Test
|
||||
void unsubscribedListenersStopReceivingEvents() {
|
||||
final TypedEventBus bus = new TypedEventBus();
|
||||
final AtomicInteger calls = new AtomicInteger();
|
||||
|
||||
final EventSubscription subscription = bus.subscribe(TestEvent.class, event -> calls.incrementAndGet());
|
||||
subscription.unsubscribe();
|
||||
|
||||
bus.publish(new TestEvent("hello"));
|
||||
|
||||
assertEquals(0, calls.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
void publishAndSubscriptionManagementAreThreadSafe() throws Exception {
|
||||
final TypedEventBus bus = new TypedEventBus();
|
||||
final AtomicInteger received = new AtomicInteger();
|
||||
final int publisherCount = 4;
|
||||
final int eventsPerPublisher = 250;
|
||||
final int subscriptionCount = 12;
|
||||
|
||||
final CountDownLatch ready = new CountDownLatch(publisherCount + subscriptionCount);
|
||||
final CountDownLatch start = new CountDownLatch(1);
|
||||
final CountDownLatch done = new CountDownLatch(publisherCount + subscriptionCount);
|
||||
try (final var executor = Executors.newFixedThreadPool(publisherCount + subscriptionCount)) {
|
||||
|
||||
for (int i = 0; i < subscriptionCount; i++) {
|
||||
executor.submit(() -> {
|
||||
ready.countDown();
|
||||
await(start);
|
||||
|
||||
final EventSubscription subscription =
|
||||
bus.subscribe(TestEvent.class, event -> received.incrementAndGet());
|
||||
bus.publish(new TestEvent("subscription-ready"));
|
||||
subscription.unsubscribe();
|
||||
done.countDown();
|
||||
});
|
||||
}
|
||||
|
||||
for (int i = 0; i < publisherCount; i++) {
|
||||
executor.submit(() -> {
|
||||
ready.countDown();
|
||||
await(start);
|
||||
|
||||
for (int j = 0; j < eventsPerPublisher; j++) {
|
||||
bus.publish(new TestEvent("payload-" + j));
|
||||
}
|
||||
done.countDown();
|
||||
});
|
||||
}
|
||||
|
||||
assertTrue(ready.await(5, TimeUnit.SECONDS));
|
||||
start.countDown();
|
||||
assertTrue(done.await(5, TimeUnit.SECONDS));
|
||||
executor.shutdownNow();
|
||||
assertTrue(received.get() >= 0);
|
||||
}
|
||||
}
|
||||
|
||||
private static void await(CountDownLatch latch) {
|
||||
try {
|
||||
latch.await();
|
||||
} catch (InterruptedException interruptedException) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new AssertionError(interruptedException);
|
||||
}
|
||||
}
|
||||
|
||||
private record TestEvent(String value) implements SimpleEvent {
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user