Search code examples
javamultithreadingsocketsobjectinputstream

ObjectInputStream fails in Java Thread


I'm unable to get input and output streams from socket, my code blocks everytime it reach the getInputStream/getOutputStream.

class Connection implements Runnable {
    private static final Logger logger = Logger.getLogger(Connection.class.getName());
    Socket connection = null;
    Boolean serverIsDown = false;
    Thread thread = null;
    ObjectInputStream ois = null;
    ObjectOutputStream oos = null;
    Context ctx = null;

    public Connection(Socket accept, Boolean serverIsDown) {
        logger.log(Level.INFO, "Connected" + accept.getRemoteSocketAddress());
        this.connection = accept;
        this.serverIsDown = serverIsDown;

        this.thread = new Thread(this, "Client Connection");
        this.thread.start();

    }

    public void init() throws IOException {
        while (true) {
            System.out.println("Hit enter to send object");
            System.in.read();
            Request request = new Request();
            oos.writeObject(request);
        }
    }

    @Override
    public void run() {
        try {
            this.ois = new ObjectInputStream(this.connection.getInputStream()); //Blocks here
            this.oos = new ObjectOutputStream(this.connection.getOutputStream());
            this.init();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

There's no output errors when it blocks.


Solution

  • as the documentation mentioned : http://docs.oracle.com/javase/7/docs/api/java/io/ObjectInputStream.html#ObjectInputStream(java.io.InputStream)

    Creates an ObjectInputStream that reads from the specified InputStream. A serialization stream header is read from the stream and verified. This constructor will block until the corresponding ObjectOutputStream has written and flushed the header.

    I suggest you use two threads handling input and output stream from accepted socket,to avoid blocking. and the other better way is to use thread pool and some async io (ex;selector) instead of assigning each accepted socket with a thread.

    also refer to the other post as below: new ObjectInputStream() blocks