Program freezes on bufferedreader close

不打扰是莪最后的温柔 提交于 2020-03-06 04:05:11

问题


Program freezes when closing buffered reader. Using forge modding API for minecraft, however I've had this issue before with standalone server side code. This particular code worked fine and then randomly started giving me this issue, not sure how to go about fixing this..

The close method:

public static void closeConnection() {
    if (keepConnection) {
        keepConnection = false;

        try {

            bufferedReader.close();
            printWriter.close();
            socket.close();
        }
        catch (IOException e) {

            e.printStackTrace();
        }

        finally{

            token = null;
        }
    }

}

I have checked to ensure that this is indeed where the freeze is occurring. Any ideas?


回答1:


Not possible. BufferedReader.close() doesn't do anything that blocks. You don't even need it. PrintWriter.close() will close everything. Remove it.

The only operation that can freeze here is closing the PrintWriter, which implies flushing its buffer, and the reason for that must be that the peer is a long way behind reading the output of this program, or isn't reading it at all.




回答2:


BufferedReader can block on close() because it contains a synchronized block on the lock instance:

synchronized (lock) {
    if (in == null)
      return;
    in.close();
    in = null;
    cb = null;
}

This means there is another Thread in your program working with the BufferedReader (possibly blocked in a read()) which is holding the lock when you try to close. The solution is to have this other thread release the lock (interrupted if necessary) to allow the close to get the lock then complete.



来源:https://stackoverflow.com/questions/42331228/program-freezes-on-bufferedreader-close

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