1

i am having a very weird situation in my code which i dont understand i am sending an object lets say O through a socket then i am changing the value of a variable in the object and sending it again but the second time when i print it on the client side, i am getting the same values as in the 1st object.

client code:

 while(true){
             try{
             order=(Order)ois.readObject();

            System.out.println(order);

             }

server code:

public void sendOrder(Order o){
    try {
        out.writeObject(o);

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

main method:

Server_Socket ss=new Server_Socket();
    ss.sendOrder(o);
    o.add(r2);
    ss.sendOrder(o);

The value is definitely changing on the serverside before i send it, but i dont understand why on the client side its not showing that r2 added in the object.

2 Answers 2

5

The objects are being cached by the ObjectOutputStream. To prevent this, call ObjectOutputStream.reset() after each write. If you are sending simple objects that don't contain other objects, use writeUnshared() instead of writeObject().

Sign up to request clarification or add additional context in comments.

6 Comments

would using reset everytime make that much of a difference on the timing
@yahh Call it whenever you want to send a fresh copy rather than every time if you like, but the overhead is pretty minimal.
as a note on this, java caches for the objects for a reason. it's java's way to telling you that it's not super good practice to be writing mutable objects over a socket. sadly, i couldn't tell you exactly why.
@AlexLynch No, it isn't "Java's way of telling you it's not super good practice to be writing mutable objects" at all. It is Java's way of implementing the Object Serialization Specification, which provides that object graphs are transmitted correctly, including cyclic graphs. It is impossible to implement that without some kind of 'handle' system that remembers what has already been transmitted and plants handles to those objects instead of retransmitting them.
@EJP can you point me to a resource that explains the process and reasoning more in-depth? i am interested, but don't fully understand based on your comment.
|
0

The objects are being cached by the IOStreams. To fix this, create a deep clone on the server prior to sending the object back. When the client pulls the object from the stream, it will have a different instance id and it will actually deserialize and instantiate the object on the client side.

Fun stuff.

1 Comment

Much too complex and error-prone. A far simpler solution exists.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.