cancel a read from an InputStream
-
22-09-2019 - |
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.
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.