Question

Currently I am using an ObjecInputStream to read from a Socket, and everything works fine using this simple code:

ObjectInputStream input = new ObjectInputStream(socket.getInputStream());
Object response = input.readObject();

Now I want to somehow cancel the read, without closing the stream, so that I can later read from it again. Is it possible?

Edit: I want to cancel the read just because it is blocking the program flow. I don't need to read the same information twice. I just want to cancel it so that I can send another request and then read the (another) response.

Was it helpful?

Solution

If you have some kind of "main" thread, then you should perform I/O off of it. Have a thread dedicated to reading and to some extends processing the input. Either queue the results to the main thread if event based, on modify the model if using a shared state design.

OTHER TIPS

See what ObjectInputStream.markSupported() returns. If it returns true, you can call ObjectInputStream.mark() at the beginning and then call ObjectInputStream.reset() to rewind the InputStream back to the place you marked so you can reuse it later.

You can use a PushBackInputStream to accomplish this. After reading some bytes you can unread the bytes.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top