views:

254

answers:

3

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.

+2  A: 

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.

Asaph
then, what to do if it returns false?BTW I don't want to read the same data twice, I just want to cancel the read so that I can send another request then read another response.
phunehehe
@phunehehe: If it returns `false` then mark/reset is not supported by this `InputStream` and this strategy won't work for you. Anyway, if you're not re-reading the same data twice (not mentioned in the original question) then the strategy wouldn't apply anyway. Why don't you simply instantiate a new `ObjectInputStream`? Object instantiation is cheap these days.
Asaph
But the program blocks when I make another call to `input = new ObjectInputStream(socket.getInputStream());` I think it must be a problem with the old stream (actually I think they are the same stream from the same socket). Do I have to create another socket?
phunehehe
@phunehehe: Yeah. Open up a new socket.
Asaph
+1  A: 

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

Vincent Ramdhanie
Thanks, please see my edit
phunehehe
+2  A: 

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.

Tom Hawtin - tackline