如何关闭等待服务器?
问题描述:
我创建了一个(单线程)服务器,并将“工作”代码放在Runnable
中。这可运行,然后在使用Java类执行人框架后台线程执行:如何关闭等待服务器?
ExecutorService exec = Executors.newSingleThreadExecutor();
exec.execute(runnable);
所以,现在,我在寻找一个好办法,关闭此服务器当机。我想添加重新启动服务器而不重新启动程序的可能性,因此终止整个过程不是一种选择。
What I have found是这样的:
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()
- 方法的事情,服务器仍然会等到最后一次连接已完成,然后关闭。
有没有任何首选的方法来处理这个?
答
因此,它在等待ServerSocket
上调用close()
的接缝是实现此目的的一种方法。在这种情况下,accept()
-method会抛出一个SocketException
,您需要捕获它。
另一个,也许更清晰的方法是使用一个“毒丸”,这是在这里详细解释说:How to interrupt a BlockingQueue which is blocking on take()?
我张贴了写在C/C++代码插座一个类似的问题,并有一个伟大的答案。我怀疑你需要使用非阻塞套接字才能达到类似的效果。你是否尝试过从其他线程关闭套接字并捕获socket.accept抛出的异常?我其实不确定这是否会奏效。 http://*.com/questions/2486335/wake-up-thread-blocked-on-accept-call – selbie 2011-12-27 23:48:13
类似的问题:http://*.com/questions/2983835/how-can-i-interrupt-a -serversocket-accept-method - 好像你需要关闭套接字。 – 2011-12-28 00:11:32
[类似的问题] [1]: - 好像你需要关闭套接字 [1]:http://*.com/questions/2983835/how-can-i-interrupt-a- serversocket-accept-method – 2011-12-28 01:55:49