Sending the same but modifed object over ObjectOutputStream


Sending the same but modifed object over ObjectOutputStream



I have the following code that shows either a bug or a misunderstanding on my part.



I sent the same list, but modified over an ObjectOutputStream. Once as [0] and other as [1]. But when I read it, I get [0] twice. I think this is caused by the fact that I am sending over the same object and ObjectOutputStream must be caching them somehow.



Is this work as it should, or should I file a bug?




3 Answers
3



The stream has a reference graph, so an object which is sent twice will not give two objects on the other end, you will only get one. And sending the same object twice separately will give you the same instance twice (each with the same data - which is what you're seeing).



See the reset() method if you want to reset the graph.



Max is correct, but you can also use:


public void writeUnshared(Object obj);



See comment below for caveat





That will work in this case, but will generally cause really odd errors. Any component object written will still be shared. So for instance if the List above was wrapped with Collections.synchronizedList, the problem would remain. writeUnshared is not very useful.
– Tom Hawtin - tackline
Sep 27 '08 at 14:15



What you probably want is:


ObjectOutputStream oos = new ObjectOutputStream(s.getOutputStream());
List same = new ArrayList();
same.add(0);
oos.writeObject(same);
oos.flush(); // flush the stream here
same.clear();
same.add(1);
oos.writeObject(same);



Otherwise the same object will be flushed twice when the stream is closed or its buffer runs out.



Just FYI, when you deserialize the objects into, let's say o1 and o2, o1 != o2.


o1


o2


o1 != o2





Nope, that didn't solve it, Max was right, use reset()
– Pyrolistical
Sep 27 '08 at 1:24





This does not work. flush() does not have the magical properties ascribed to it here.
– EJP
Dec 12 '17 at 7:17


flush()






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

How to input without newline? (Python)

C++ thread error: no type named ‘type’ MINGW

Analog for TagView in flutter