序列化:JVM如何跟踪已将所有对象写入流中

Sas*_*wat 2 java serialization

在以下程序中.

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.txt"));

        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;
    }

}
Run Code Online (Sandbox Code Playgroud)

上述程序的输出是20 20.

这意味着当它第二次写入相同的对象而不是写入对象时,它已经编写了一个处理程序.

我怀疑JVM是如何跟踪已经将所有对象写入流的?

Bra*_*lor 7

ObjectOutputStream的类是负责处理此逻辑.

从Java 对象序列化常见问题解答:

ObjectOutputStream类跟踪它序列化的每个对象,如果在随后的时间将对象写入流中,则仅发送句柄.这是它处理对象图的方式.相应的ObjectInputStream会跟踪它创建的所有对象及其句柄,因此当再次看到句柄时,它可以返回相同的对象.输出和输入流都保持此状态,直到它们被释放.