gpt4 book ai didi

java - 如何正确关闭 BlockingQueue?

转载 作者:行者123 更新时间:2023-11-29 08:46:53 28 4
gpt4 key购买 nike

我有一个在单个后台线程上处理工作事件的 BlockingQueue。各种线程调用 add 将一些工作添加到队列中,单个后台线程调用 take 获取工作并一次处理一个。最终可能是停止处理工作的时候了,我想确保请求工作的调用者要么得到他们的结果,要么得到 null 表明他们的工作没有完成,因为 BlockingQueue 正在关闭。

如何干净利落地停止接受新工作,我能想到的最好的方法是将 BlockingQueue 字段设置为 null 然后捕获 NullPointerExceptionadd 被调用时。在将该字段设置为 null 之前,我将保留指针的本地副本,以便在它停止接受工作后我可以将其耗尽。我认为这会奏效,但似乎有点老套,有没有合适的方法来做到这一点?

现在的代码是这样的:

ArrayBlockingQueue<Command> commandQueue = 
new ArrayBlockingQueue<Command>(100, true);

public boolean addToQueue(Command command) {
try {
return commandQueue.add(command);
} catch (IllegalStateException e) {
return false;
}
}

@Override
public void run() {
try {
while (!Thread.currentThread().isInterrupted()) {
Command command = commandQueue.take();
// ... work happens here
// result is sent back to caller
command.provideResponseData(response);
}
} catch (InterruptedException e) {
// Break out of the loop and stop
}

// TODO: stop accepting any new work, drain the queue of existing work
// and provide null responses
}

最佳答案

与其使用 BlockingQueue 和工作线程,不如考虑使用单线程 ThreadPoolExecutor。像这样:

private class CommandRunner implements Runnable {
public CommandRunner(Command command) {
this.command = command;
}

public void run() {
// ... work happens here
// result is sent back to caller
command.provideResponseData(response);
}
}

private ExecutorService commandExecutor = Executors.newSingleThreadExecutor();

public boolean addToQueue(Command command) {
commandExecutor.submit(new CommandRunner(command));
}

然后您的关闭方法可以委托(delegate)给执行者。

关于java - 如何正确关闭 BlockingQueue?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24789741/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com