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