开发者

Serialization : How does JVM keep track of which all object have already been written to the stream

开发者 https://www.devze.com 2023-04-12 01:47 出处:网络
In the following program. public class SerialExample { public static void main(String args[]) throws Exception{

In the following program.

public class SerialExample {
    public static void main(String args[]) throws Exception{
        ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream("out.txt"));

        Car c = new Car(20);

        os.writeObject(c);

        c.setSpeed(30);

        os.writeObject(c);

        os.close();



        ObjectInputStream in = new ObjectInputStream(new FileInputStream("out.tx开发者_StackOverflowt"));

        Car d = (Car)in.readObject();
        Car e = (Car)in.readObject();

        System.out.println(d.getSpeed() + "   " + e.getSpeed());

        in.close();
    }
}


class Car implements Serializable{
    private int speed;

    Car(){
        speed = 1;
    }

    Car(int speed){
        this.speed = speed;
    }

    public int getSpeed(){
        return speed;
    }

    public void setSpeed(int speed){
        this.speed = speed;
    }

}

The output of the above program is 20 20.

That means when it is writing the same object the second time instead of writing the object it has written a handler.

My doubt is how does JVM keep track of which all object have already been written to the stream?


The ObjectOutputStream class is responsible for handling this logic.

From the Java Object Serialization FAQ:

The ObjectOutputStream class keeps track of each object it serializes and sends only the handle if the object is written into the stream a subsequent time. This is the way it deals with graphs of objects. The corresponding ObjectInputStream keeps track of all of the objects it has created and their handles so when the handle is seen again it can return the same object. Both output and input streams keep this state until they are freed.

0

精彩评论

暂无评论...
验证码 换一张
取 消