Broadcast events asynchronously.

This commit is contained in:
akwizgran
2018-11-07 13:26:00 +00:00
parent 8b3164e107
commit c3b5b04b71
15 changed files with 104 additions and 8 deletions

View File

@@ -160,13 +160,15 @@ class DatabaseComponentImpl<T> implements DatabaseComponent {
public void endTransaction(Transaction transaction) {
try {
T txn = txnClass.cast(transaction.unbox());
if (!transaction.isCommitted()) db.abortTransaction(txn);
if (transaction.isCommitted()) {
for (Event e : transaction.getEvents()) eventBus.broadcast(e);
} else {
db.abortTransaction(txn);
}
} finally {
if (transaction.isReadOnly()) lock.readLock().unlock();
else lock.writeLock().unlock();
}
if (transaction.isCommitted())
for (Event e : transaction.getEvents()) eventBus.broadcast(e);
}
@Override

View File

@@ -0,0 +1,32 @@
package org.briarproject.bramble.event;
import org.briarproject.bramble.api.event.EventExecutor;
import java.util.concurrent.Executor;
import javax.inject.Singleton;
import dagger.Module;
import dagger.Provides;
import static java.util.concurrent.Executors.newSingleThreadExecutor;
/**
* Default implementation of {@link EventExecutor} that uses a dedicated thread
* to notify listeners of events. Applications may prefer to supply an
* implementation that uses an existing thread, such as the UI thread.
*/
@Module
public class DefaultEventExecutorModule {
@Provides
@Singleton
@EventExecutor
Executor provideEventExecutor() {
return newSingleThreadExecutor(r -> {
Thread t = new Thread(r);
t.setDaemon(true);
return t;
});
}
}

View File

@@ -7,6 +7,7 @@ import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
import java.util.Collection;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.Executor;
import javax.annotation.concurrent.ThreadSafe;
@@ -16,6 +17,11 @@ class EventBusImpl implements EventBus {
private final Collection<EventListener> listeners =
new CopyOnWriteArrayList<>();
private final Executor eventExecutor;
EventBusImpl(Executor eventExecutor) {
this.eventExecutor = eventExecutor;
}
@Override
public void addListener(EventListener l) {
@@ -29,6 +35,8 @@ class EventBusImpl implements EventBus {
@Override
public void broadcast(Event e) {
for (EventListener l : listeners) l.eventOccurred(e);
eventExecutor.execute(() -> {
for (EventListener l : listeners) l.eventOccurred(e);
});
}
}

View File

@@ -1,6 +1,9 @@
package org.briarproject.bramble.event;
import org.briarproject.bramble.api.event.EventBus;
import org.briarproject.bramble.api.event.EventExecutor;
import java.util.concurrent.Executor;
import javax.inject.Singleton;
@@ -12,7 +15,7 @@ public class EventModule {
@Provides
@Singleton
EventBus provideEventBus() {
return new EventBusImpl();
EventBus provideEventBus(@EventExecutor Executor eventExecutor) {
return new EventBusImpl(eventExecutor);
}
}