Question

I'm taking over an existing JAVA project which containing the following code:

class ConnectionHandler extends Thread {
    private Socket socket;

    public ConnectionHandler(Socket s) {
        this.socket = s;
    }

    private void doSthForRequest(ObjectInputStream in, ObjectOutputStream out) throws Exception {
        // Do something and write output to out:
        // out.writeObject(someOutput);
    }

    public void run() {

        ObjectOutputStream out = null;
        ObjectInputStream in = null;

        try {
            in = new ObjectInputStream(socket.getInputStream());
            out = new ObjectOutputStream(socket.getOutputStream());
            while (true) {
                out.reset();
                doSthForRequest(in, out);
            }
        } catch (Exception ex) {
            if (out != null && !socket.isOutputShutdown()) {
                try {
                    out.writeObject(ex);
                    out.flush();
                } catch (Exception ex2) {}
            }
        } finally {
            if (out != null) {
                try {
                    out.reset(); // any reason for this?
                } catch (Exception ee) {}
            }
            if (out != null) {
                try {
                    out.close();
                } catch (Exception ee) {}
            }
            try {
                socket.close();
            } catch (Exception e) {}
        }

        socket = null;
    }
}

There are ConnectionHandler threads which serving request and producing output on a socket. And my question is:

Does the reset() call still make any sense if there is a close() call immediately after it?

The original author just leaves one line comment // clear outputstream cache which makes me confused...

Appreciate your help!

Was it helpful?

Solution

No. reset() sends a tag over the wire that tells the peer to clear its handle table. As you're about to close the stream anyway, the reset operation has no meaning, and it's an extra network operation to go wrong. Just close it.

As for other problems:

  1. Construct the ObjectOutputStream before the ObjectInputStream. Otherwise a deadlock can occur.

  2. Use the try-with-resources syntax here. It will simplify the code a lot.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top