Is setting a timeout on ObjectInputStream.readObject() safe?
I have an ObjectInputStream
connected to an ObjectOutputStream
through a socket, and I've been using Socket.setSoTimeout()
to make ObjectInputStream.readObject()
only block for 100ms. Since I started doing this I've been getting alot of StreamCorruptedError
's while cal开发者_开发知识库ling readObject()
. Could the timeout be to blame?
I have a thread constantly getting new data through this function but I want to be able to stop it by setting a boolean to false. The thread has to keep polling the boolean and can't if it's blocked by readObject()
You can use Thread.interrupt to let it throw an InterruptedException
, or in this case an InterruptedIOException
. Make sure you don't swallow exceptions!
If you set the timeout shorter than the normal delays which might occur in reading a stream, you can expect the timeout to be in effect when the stream is still properly active.
100 ms seems like a long time, but not if there's disk or network traffic involved. Try timing out on something ridiculous, like a second.
精彩评论