I have two threads, let's call them A
and B
. A
is constantly looking for packets from the ObjectInputStream
via the readPacket
function (this would be while(true)
in a thread etc)
While A
is looking for these packets, I want B
to write a packet to the ObjectOutputStream
via the writePacket
function.
But I enter a deadlock whenever I want to do this; I don't understand how two different functions can deadlock each other?
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.concurrent.locks.ReentrantLock;
public class ConnectionBay
{
private Socket connection;
private ObjectOutputStream output_stream;
private ObjectInputStream input_stream;
ConnectionBay(Socket socket) throws IOException{
this.connection = socket;
this.output_stream = new ObjectOutputStream(connection.getOutputStream());
this.output_stream.flush();
this.output_stream.reset();
this.input_stream = new ObjectInputStream(connection.getInputStream());
}
public synchronized void writePacket(Packet packet) throws IOException{
this.output_stream.writeObject(packet);
this.output_stream.flush();
this.output_stream.reset();
}
public synchronized Packet readPacket() throws IOException, ClassNotFoundException{
return (Packet)this.input_stream.readObject();
}
}