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

feat(eventLoop): the visibility of the shutdown flag for the event loop and optimizations for graceful shutdown #1796

Merged
merged 6 commits into from
Aug 23, 2024
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
Original file line number Diff line number Diff line change
Expand Up @@ -17,14 +17,21 @@
import java.util.concurrent.Executor;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;

public class EventLoop extends Thread implements Executor {
private final Logger logger;
private BlockingQueue<Runnable> tasks;
private boolean shutdown = false;
private volatile boolean shutdown;
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Did not see when shutdown = true was set

private CompletableFuture<Void> shutdownCf = new CompletableFuture<>();

static final Runnable WAKEUP_TASK = new Runnable() {
@Override
public void run() {
}
};

@SuppressWarnings("this-escape")
public EventLoop(String name) {
super(name);
Expand All @@ -33,10 +40,14 @@ public EventLoop(String name) {
start();
}

@Override
public void run() {
while (true) {
try {
Runnable task = tasks.poll(100, TimeUnit.MILLISECONDS);
if (task == WAKEUP_TASK) {
task = null;
}
if (task == null) {
if (shutdown) {
shutdownCf.complete(null);
Expand All @@ -57,7 +68,7 @@ public void run() {
}
}

public CompletableFuture<Void> submit(Runnable task) {
public synchronized CompletableFuture<Void> submit(Runnable task) {
check();
CompletableFuture<Void> cf = new CompletableFuture<>();
tasks.add(() -> {
Expand All @@ -72,13 +83,16 @@ public CompletableFuture<Void> submit(Runnable task) {
}

@Override
public void execute(Runnable task) {
public synchronized void execute(Runnable task) {
check();
tasks.add(task);
}

public CompletableFuture<Void> shutdownGracefully() {
public synchronized CompletableFuture<Void> shutdownGracefully() {
shutdown = true;
if (!shutdownCf.isDone() && tasks.isEmpty()) {
tasks.add(WAKEUP_TASK);
}
return shutdownCf;
}

Expand Down
Loading