I have written a client that reads TCP messages using an ObjectInputStream
in a separate thread from the main thread. I am using Eclipse and although no exception is thrown in the console, at random times the debug window will open and show the following error in what I assume is the Thread stack trace:
Thread[Thread-5](Suspended (exception ThreadDeath))
objectinputstream.readobject() line: not available [local variables unavailable]
ReceiveRunnable.run()line:25
Thread.run()line:not available
This the code that the exception points to:
class ReceiveRunnable implements Runnable {
Object receivedObject;
public void run() {
while (true) {
try {
receivedObject = client.objectInStream.readObject(); //line 25
} catch (IOException e) {
// client.reconnectToServer();
// System.out.println("IO exception in run()");
// System.out.println(e);
e.printStackTrace();
} catch (ClassNotFoundException e) {
System.out.println("Class Not Found exception in run()");
System.out.println(e);
e.printStackTrace();
} catch (Exception e) {
System.out.println("Exception in ReceiveRunnable.run()");
System.out.println(e.toString());
e.printStackTrace();
}
}
}
}
client.objectInStream
is created in the Client
class:
void connectToServer(){
try {
connected = false;
socket = new Socket(host, port);
System.out.println("<Connected> " + socket);
objectInStream = new ObjectInputStream(socket.getInputStream());
objectOutStream = new ObjectOutputStream(socket.getOutputStream());
receiveThread = new Thread(new ReceiveRunnable(this, "receive"));
receiveThread.start();
/* used to periodically ping the server*/
long delay = 0;
long period = 5000;
connTimer.schedule(clientCheckConnTimerTask, delay, period);
connected = true;
sendString("[conn]" + clientUUID);
} catch (IOException e) {
msgBox.set2LineOkMessage("Can not connect to server.", "");
msgBox.show();
}
}
Can anyone tell me what is causing the problem and how I might resolve please?
If that try
isn't followed by a catch (EOFException exc)
that closes the socket and breaks out of the loop, your code is incorrect.
You should always create the ObjectOutputStream
before the ObjectInputStream
for the same socket, not afterwards, otherwise you can get deadlocks.