Reputation: 2096
I have 2 threads - one is to receiving messages and second is both for receiving and sending.
PrintStream os = new PrintStream(sock.getOutputStream());
BufferedReader is = new BufferedReader(new InputStreamReader(sock.getInputStream()));
ServerThread server = new ServerThread(sock, maxid, os,is);
OutputThread out = new OutputThread(sock, maxid, os,is);
Then, when I close connection I want to close is and os properly, but how to do it both in 2 threads? I get java.net.SocketException
in ServerThread
public ServerThread(..){
try{
//here I use is and os
} finally {
disconnect();
}
}
public void disconnect() {
try {
System.out.println(addr.getHostName()+ " disconnected");
os.close();
try {
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} finally {
this.interrupt();
}
}
Upvotes: 1
Views: 139
Reputation: 7234
Your threads are recieving the is and os from external sources and hence the responsibility of closing the streams should lie with the external entity. Do not close them inside the threads. Handle it externally in the place where they are created.
Upvotes: 1
Reputation: 1125
Look at http://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/CyclicBarrier.html This can be used for threads to wait for each other before one of them close the stream.
Upvotes: 0