如何关闭等待的服务器?

发布于 2024-12-23 05:27:14 字数 955 浏览 1 评论 0原文

我创建了一个小型(单线程)服务器并将“工作”代码放入 Runnable 中。然后使用 Javas Executor Framework 在后台线程中执行此可运行程序:

ExecutorService exec = Executors.newSingleThreadExecutor();
exec.execute(runnable);

所以现在,我正在寻找一种关闭此服务器的好方法。我想添加在不重新启动程序的情况下重新启动服务器的可能性,因此终止整个过程不是一个选项。

我发现的是一些东西像这样:

class LifecycleWebServer {
    private final ExecutorService exec = ...;

    public void start() throws IOException {
        ServerSocket socket = new ServerSocket(80);
        while (!exec.isShutdown()) {
            final Socket conn = socket.accept();
            // Do stuff with the connection...
        }
    }

    public void stop() { exec.shutdown(); }
}

令我困扰的是,如果程序已到达第 7 行(socket.accept()),并且我调用 stop() 方法,服务器仍会等待建立最后一个连接然后关闭。

有没有更好的方法来处理这个问题?

I created a little (single thread) server and put the "work"-code in a Runnable. This runnable is then executed in a background-thread using Javas Executor Framework:

ExecutorService exec = Executors.newSingleThreadExecutor();
exec.execute(runnable);

So now, I'm searching for a good way to shut this server down. I want to add the possibility to restart the Server without restarting the program, so terminating the whole process is not an option.

What I have found is something like this:

class LifecycleWebServer {
    private final ExecutorService exec = ...;

    public void start() throws IOException {
        ServerSocket socket = new ServerSocket(80);
        while (!exec.isShutdown()) {
            final Socket conn = socket.accept();
            // Do stuff with the connection...
        }
    }

    public void stop() { exec.shutdown(); }
}

The thing that bothers me is, that if the program has reached line 7 (socket.accept()), and I call the stop()-method, the Server will still wait until one last connection was made and then shutdown.

Is there any preferred way to deal with this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

横笛休吹塞上声 2024-12-30 05:27:14

因此,在等待的 ServerSocket 上调用 close() 是实现此目的的一种方法。在这种情况下,accept() 方法将抛出 SocketException,您需要捕获该异常。

另一种可能更清晰的方法是使用“毒丸”,此处详细解释:如何中断在 take() 上阻塞的 BlockingQueue?

So, it seams that calling close() on the waiting ServerSocket is one way to do this. In that case, the accept()-method will throw a SocketException, which you'll need to catch.

Another, maybe clearer way is to use a "Poison Pill", which is explained in detail here: How to interrupt a BlockingQueue which is blocking on take()?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文