Why is Java’s Object Stream returning the same object each time I call readObject?

Forgive the pseudocode – my wireless networks is down, and I can’t copy the code from my offline computer onto StackExchange at the moment.

I have two java applications, connected via java.net.* sockets. I am trying to pass “Message” objects from one to the other with via objectinput/output streams.

Here’s what I’m doing:

Class Message implements Serializable
{
  String text
  int data
     public Message(String txt, int dat)
     {
      this.text = txt;
      this.data = dat;
     }
     string toString()
     {
      return text + " " + data;
     }
}

Server:

Server has a Queue called Outbox

for(int i = 0; i < 1000; i++)
 { 

 Message adding = new Message("Hello!",i);
 Outbox.add(temp)
 Message temp =     Outbox.poll();
 out.writeObject(temp);
  system.out.println(temp)
 }

Client:

for(int i = 0; i < 1000; i++)
{
  Message temp;
  temp = in.readObject()
  system.out.println(temp)
}

Now I hope it’s apparent that I expect the consoles of each program to look identical. Instead, this is what I’m geting.

Server

Hello 0
Hello 1
Hello 2
Hello 3...

Client

Hello 0
Hello 0
Hello 0
Hello 0...

So it looks like the Message Objects are being read but not removed from the Stream.

How can I unclog my streams and get them synchronized, as expected?

Answer

the classic cause of this problem is sending the same object reference multiple times. the Object stream impls preserve object reference identity and on the receiving end you will get the same object back on each readObject() call (even if you have modified the object on the sending side!). your pseudo code is correct, however the question is whether or not it accurately reflects your actual code.

if your problem is a reference problem, you can solve the problem by either sending different object instances each time, or usingwriteUnshared() and/or calling reset() between each writeObject() call. using writeUnshared() will force the main object to be a new object instance on the receiving end, but other objects which may be referenced by this object may still be shared references. on the other hand, calling reset() will flush all cached objects on the receiving end, so all object references on the receiving end will be new references. which one is better for managing the data over the wire is up to your use case, however, for long-running streams, it’s always good to periodically call reset(), as this will free up memory which will build up over time (this is a common, but subtle “memory leak” when using Object streams).

Leave a Reply

Your email address will not be published. Required fields are marked *