gpt4 book ai didi

Java ExecutorService 无法在执行服务器时关闭

转载 作者:行者123 更新时间:2023-12-02 03:07:17 25 4
gpt4 key购买 nike

我不确定关闭我的服务器(和 ExecutorService)到底是什么问题。我启动 ServerMain 并按 Enter 键,这会使用 socket.close() 启动 server.shutdown() 方法,但不会抛出 SocketException。我不知道这是否与 ExecutorService 无法关闭有关。这是代码:

public class ServerMain {

public static void main(String[] args) throws DirectoryServerException, IOException {
TCPDirectoryServer server = new TCPDirectoryServer();
ExecutorService serverExecutor = Executors.newSingleThreadExecutor();
try {
server.start(1337);
serverExecutor.execute(server);
System.out.println("Server started. Press enter to terminate.");

System.in.read();

server.shutdown();
System.out.println("Server is shut down...");
} finally {
serverExecutor.shutdown();
while (!serverExecutor.isTerminated()) {
try {
if (!serverExecutor.awaitTermination(5, TimeUnit.SECONDS)) {
System.err.println("Problem with shutting down the Executor");
serverExecutor.shutdownNow();
}
} catch (InterruptedException ignore) {
}
}
}
}
}

这是服务器:

public class TCPDirectoryServer implements DirectoryServer {
private int port;
private ConcurrentHashMap<ParseDirectory, Histogram> cache;
private List<ClientHandler> clientHandlerList;
private ExecutorService clientExecutorService;
private Socket socket;

public TCPDirectoryServer() {
super();
this.cache = new ConcurrentHashMap<ParseDirectory, Histogram>();
this.clientHandlerList = new LinkedList<ClientHandler>();
this.clientExecutorService = Executors.newCachedThreadPool();
}

@Override
public void start(int port) throws DirectoryServerException {
this.port = port;
}

@Override
public void disconnect(ClientHandler clientHandler) {
clientHandlerList.remove(clientHandler);

}

@Override
public void shutdown() throws DirectoryServerException {
try {
socket.close();
} catch (IOException e) {
throw new DirectoryServerException(e);
}
}

@Override
public void run() {
try (ServerSocket serverSocket = new ServerSocket(port)) {
while (true) {
socket = serverSocket.accept();
clientHandlerList.add(connect(socket));
}
} catch (SocketException e) {
System.err.println("AAAA");
System.out.println("Server is shutting down");

} catch (IOException e) {
System.out.println("Something failed " + e.getMessage());
}
}

最佳答案

这部分:

    while (true) {
socket = serverSocket.accept();
clientHandlerList.add(connect(socket));
}

...当您调用 shutdown 时,不会抛出 SocketException,因为您正在关闭那里的客户端套接字(最后连接的套接字)。 ServerSocket 仍然打开并等待传入​​请求。

关于Java ExecutorService 无法在执行服务器时关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41570948/

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