Java try-with-recourses陷入困境

时间:2017-05-09 13:23:02

标签: java sockets try-with-resources

我有一个经典的服务器多客户端程序。服务器侦听ServerSocket,对于每个传入的套接字,它构建一个新的Runnable类并在ExecuteService中执行它。

在Runnable类的run方法中,我打开try-with-resources块,在try中我有一个while循环,它从inputstream读取并写入outputstream,直到它从客户端收到FIN命令。一切正常,客户端断开连接。运行到达finally块并打印一些东西进行测试,但是它不会退出try块,因此它不会退出run方法而且我被困在运行某处,也许是输入流的read方法。

如果有兴趣的话,我可以发布代码。

如何强制关闭finally中的所有内容并退出run方法?

代码:
Server.java:

public static void main(String[] args) {
    playersReady = new ArrayList<Integer>();
    ServerSocket server = null;
    try {
        server = new ServerSocket(Consts.PORT);
        ExecutorService service = Executors.newFixedThreadPool(characters.size());
        while(playersReady.size()<characters.size()){
            RequestHandler handler = new RequestHandler(server.accept());
            service.execute(handler);
        }
        service.shutdownNow();
        service.shutdown();
        while(!service.isTerminated()){}

        System.out.println("finished");

RequestHandler.java

public final class RequestHandler implements Runnable {

    .....

public void run() {
    //DataOutputStream output = null;
    //DataInputStream input = null;

    try (DataOutputStream output = new DataOutputStream(socket.getOutputStream());
            DataInputStream input = new DataInputStream(socket.getInputStream())){
        // socket.setSoTimeout(500);
        handleReady(input.readUTF().split(" "), output);
        while (/*!shutdown && !socket.isClosed() && */socket.isConnected()) {

            System.out.println("check before read " + character.getId());
            String request = input.readUTF();
            System.out.println("check after read " + character.getId());

            System.out.println("-----------------------------------" + request);
            if (shutdown) {
                socket.shutdownInput();
                socket.getOutputStream().flush();
                socket.shutdownOutput();
                break;
            }
            String[] requestParser = request.split(" ");
            if (requestParser[1].equals("DMG")) {
                // handle damage request
                handleDamage(requestParser, output);
            } else if (requestParser[1].equals("BND")) {
                // handle bandage request
                handleBandage(requestParser, output);
            } else if (requestParser[1].equals("FIN")) {
                // handle finish request
                handleFin();
                if (!socket.isClosed())
                    socket.shutdownInput();
                if (!socket.isClosed()) {
                    socket.getOutputStream().flush();
                    socket.shutdownOutput();
                }
                shutdown = true;
                break;
            } else {
                break;
            }
        }
    } catch (SocketTimeoutException e) {
        System.out.println(e.getMessage());
    } catch (IOException e) {
        e.printStackTrace();
        shutdown = true;
        break;
    } catch (Throwable e) {
        e.printStackTrace();
    } finally {
        try {
            System.out.println("finished");

            if (!socket.isClosed())
                socket.shutdownInput();
            if (!socket.isClosed()) {
                socket.getOutputStream().flush();
                socket.shutdownOutput();
                socket.close();
            }
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    System.out.println("Done run");
}

...

最后打印的System.out.println("finished"), 但是run方法结束时System.out.println("Done run")没有!!

为什么?
它停留在run方法中,我认为在readUTF调用中,但我关闭了所有资源!

1 个答案:

答案 0 :(得分:3)

你在该行之前返回,这就是它没有运行的原因。无论如何都会运行finally块,因为它是一个finally块。最后总是运行块,此规则只有一个例外:System.exit(),但事实并非如此。