在ObjectInputStream.readObject()上设置超时是否安全? [英] Is setting a timeout on ObjectInputStream.readObject() safe?

查看:176
本文介绍了在ObjectInputStream.readObject()上设置超时是否安全?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 ObjectInputStream 通过套接字连接到 ObjectOutputStream ,我一直在使用 Socket.setSoTimeout()使 ObjectInputStream.readObject()仅阻止100ms。自从我开始这样做以来,我在调用 readObject()时得到了很多 StreamCorruptedError 。超时是否可以归咎于?

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 calling readObject(). Could the timeout be to blame?

推荐答案


我有一个线程不断通过此函数获取新数据但我希望能够通过将布尔值设置为false来阻止它。线程必须保持轮询布尔值,如果它被readObject()阻止则不能。

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()

你可以使用Thread.interrupt让它它抛出一个 InterruptedException ,或者在这种情况下是 InterruptedIOException 。确保你不要吞下例外!

You can use Thread.interrupt to let it throw an InterruptedException, or in this case an InterruptedIOException. Make sure you don't swallow exceptions!

这篇关于在ObjectInputStream.readObject()上设置超时是否安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆