2

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?

user207421
  • 305,947
  • 44
  • 307
  • 483
  • And what is the crash? i.e. what error/exception and what message? – Salem Feb 19 '17 at 19:01
  • @1blustone No message, it just freezes up. In my minecraft example for instance, the client just hangs and i have to force close and restart – user3681585 Feb 19 '17 at 19:17
  • A freeze is not a crash. A crash is accompanied by an exit and a core dump or stack trace. A freeze is caused by a block or a deadlock. – user207421 Feb 19 '17 at 21:26

2 Answers2

5

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.

Paul Jowett
  • 6,513
  • 2
  • 24
  • 19
0

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.

user207421
  • 305,947
  • 44
  • 307
  • 483
  • 1
    Removing bufferedReader.close fixes my problem entirely, like I said previously my issue seems to be with that one line. Does the closing of printWriter actually close the reader too? – user3681585 Feb 20 '17 at 02:02
  • Closing either the input stream or the output stream of a socket closes the socket. You need to close the `PrintWriter` because it implies a `flush()`, which is the only place you can possibly be blocking. – user207421 Feb 20 '17 at 09:07
  • Yes, that makes sense. I can close the writer just fine, thank you for the clarification – user3681585 Feb 20 '17 at 13:59