Is it ok to be calling reset() on an ObjectOutputStream very frequently?

末鹿安然 提交于 2019-12-01 07:10:40

问题


I read somewhere which has left me unsure and looking for an alternative way. Does calling reset() too frequently cause strain on the network, or unnecessary for this?

I'm sending an object using TCP over an ObjectOutputStream. The objects values get changed before it is written again. Now the same Object but containing different values, without the reset() it resends a reference of the cached object sent before it, which is read to have no changes. I'm not sure if using reset() is a good idea due to such strain. Should I be looking for another way?

Example code would be like:

Socket socket = new Socket(ip, port);

BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream());
ObjectOutputStream oos = new ObjectOutputStream(bos);

while(true){
    oos.writeObject(object);
    oos.flush();
    oos.reset();

    object.x++;
}

回答1:


Does calling reset() too frequently cause strain on the network

Compared to what? If you need to reset, it is because you need to transmit previously transmitted objects with new values. If you don't need to do that, don't call it. If you do need to do it, network overheads are irrelevant to the functional requirement.

or unnecessary for this?

Eh? Translation please?

I'm sending an object using TCP over an ObjectOutputStream. The objects values get changed before it is written again

So you need to either call reset() or use writeUnshared().

Now the same Object but containing different values, without the reset() it resends a reference of the cached object sent before it, which is read to have no changes.

Correct. So you can't do that.

I'm not sure if using reset() is a good idea due to such strain.

What strain? The only 'strain' is that you are transmitting the new value of the object, and your functional requirement dictates that you must do that. So you don't have a choice.

Should I be looking for another way?

There isn't another way. Either you have to transmit the new value of the object or you don't. If you do, all solutions are essentially equivalent. If you don't, don't.



来源:https://stackoverflow.com/questions/22264500/is-it-ok-to-be-calling-reset-on-an-objectoutputstream-very-frequently

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!