Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Ensure that Dispatcher can't be started more than one time #632

Merged
merged 1 commit into from
Sep 18, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 19 additions & 16 deletions src/main/java/com/pivovarit/collectors/Dispatcher.java
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Function;
import java.util.function.Supplier;

Expand All @@ -31,7 +32,8 @@ final class Dispatcher<T> {
private final Executor executor;
private final Semaphore limiter;

private volatile boolean started = false;
private final AtomicBoolean started = new AtomicBoolean(false);

private volatile boolean shortCircuited = false;

private Dispatcher(Executor executor, int permits) {
Expand All @@ -44,22 +46,23 @@ static <T> Dispatcher<T> of(Executor executor, int permits) {
}

void start() {
started = true;
dispatcher.execute(() -> {
try {
while (true) {
Runnable task;
if ((task = workingQueue.take()) != POISON_PILL) {
limiter.acquire();
executor.execute(withFinally(task, limiter::release));
} else {
break;
if (!started.getAndSet(true)) {
dispatcher.execute(() -> {
try {
while (true) {
Runnable task;
if ((task = workingQueue.take()) != POISON_PILL) {
limiter.acquire();
executor.execute(withFinally(task, limiter::release));
} else {
break;
}
}
} catch (Throwable e) {
handle(e);
}
} catch (Throwable e) {
handle(e);
}
});
});
}
}

void stop() {
Expand All @@ -73,7 +76,7 @@ void stop() {
}

boolean isRunning() {
return started;
return started.get();
}

CompletableFuture<T> enqueue(Supplier<T> supplier) {
Expand Down