Using resources of try-with-resources outside try

好久不见. 提交于 2021-01-28 02:44:07

问题


I'm using SocketChannel to send message between a server and a client. Once a client connects with a server, the server opens the InputStreams and OutputStream in a try-with-resources try, to receive messages from the client and send messages to the client, like so:

try (ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
     ObjectInputStream in = new ObjectInputStream(socket.getInputStream())) {}

I want to access out outside of the try. The try contains a while loop that repeatedly checks if messages has arrived on in, which works fine.

I tried setting a global variable, say global_out, by doing:

ObjectOutputStream global_out;
...
try (ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
     ObjectInputStream in = new ObjectInputStream(socket.getInputStream())) {

    setOut(out);
    while(should_check) {
        Object message = in.readObject();   
        //do something
    }
}

And then I tried writing to this OutputStream, like so:

public void sendMessage(Object message) {
    global_out.writeObject(message);
}

I only call sendMessage(Object) when should_ceck is true and test if global_out is null, which it isn't. However, sendMessage(Object) never returns. If global_out isn't null, it must have been set to something, so why can't the resources be used before the try-with-resources terminates?

Is there any way I can get around this?

来源:https://stackoverflow.com/questions/22663403/using-resources-of-try-with-resources-outside-try

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!