Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java input stream buffers object?

I have a client-server application where the server sends all clients a list of all clients every time a new client socket joins. The problem is, that when a new client joins it gets the right list but the old clients get the old list they got when joining themselves. Sort of like they take the same object from the input stream every time.

Can I somehow flush the input stream?

Reading the object:

while((inObject = in.readObject()) != null) {
   ...
}

Sending the object:

out.writeObject(object);
like image 991
Rob Fox Avatar asked Feb 25 '23 06:02

Rob Fox


2 Answers

ObjectOutputStream.reset() is what you're looking for.

It will also prevent you from running out of memory, which could otherwise happen. The reason is that the ObjectInput/OutputStream classes cache all objects that have been sent through them, which also prevents those objects from being garbage collected. This is necessary to deal with circular references, and also improves performance when objects are sent multiple times.

like image 126
Michael Borgwardt Avatar answered Feb 26 '23 21:02

Michael Borgwardt


I suspect the problem is that you're modifying existing objects, then reusing the existing ObjectOutputStream. Call reset on the ObjectOutputStream to effectively clear its cache of references to potentially-modified objects.

like image 32
Jon Skeet Avatar answered Feb 26 '23 20:02

Jon Skeet