Fabrizio R.
Fabrizio R.

Reputation: 126

One issue using socket and threads

I'm working with sockets and threads, and I have a problem that I don't understand. After the accept(), I call thread (using pool created with ThreadPoolExecutor). The thread called (waitReplay) does receive an object (one command), it creates a new ObjectInputStream, then it does something and at last, it closes the ObjectInputStream. When I debug I see that closing OjectInputStream (ois.close();) the socket also was closed even the soc.close() is not invoked. Of course, the next thread doesn't work.

This is the calling code:

try {
Socket client = server.accept();    // accept che va in timeout
while (count.getCount()>0)
    pool.execute(new WaitReplay(client, count));

client.close();
accepted = true;
System.out.println("Quorum ragiunto!");

}

And the called thread:

public class WaitReplay implements Runnable {
    protected Socket soc;
    protected Counter cnt;

    public WaitReplay(Socket soc, Counter cnt) {
        this.soc = soc;
        this.cnt = cnt;
    }

    public void run()  {
        ObjectInputStream   ois;    // input stream
        Message msg;
        InputStream in;

        try {
            in = soc.getInputStream();
            ois = new ObjectInputStream(in);

            msg = (Message) ois.readObject();

            System.out.println("Ricevuto: " + msg.getCmd() + ": Quorum " + cnt.getCount());
            if (msg.getCmd() == Cmnd.OK) {
            cnt.decrement();                            
        }
                ois.close();

        }
        catch (Exception e) {
            System.out.println("schiatto dentro waitreply");
            e.printStackTrace();
            return;
        }       
    }
}

Upvotes: 1

Views: 308

Answers (1)

minus
minus

Reputation: 2786

This is the normal behavior. Closing a stream will close the underlying stream.

You should not close the ObjectInputStream if you want to keep the SocketInputStream open.

Upvotes: 1

Related Questions