2/28/2007

Static gets serialized..?

Now dont jump into conclusions before you read this.

import java.io.*;
public class Ser implements Serializable {
static int var = 9;

void set() {
var = 100;
}
}

public class DumpSer {
public static void main(String[] args) throws Exception {
Ser kk = new Ser();
kk.set();
File outFile = new File("out.dmp");
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(outFile));
out.writeObject(kk);
out.close();
}
}

public class LoadSer {
public static void main(String[] args) throws Exception {
File inFile = new File("out.dmp");
ObjectInputStream in = new ObjectInputStream(new FileInputStream(inFile));
Ser jj = (Ser)in.readObject();
in.close();
System.out.println("Val -> "+jj.var);
}
}

After compilation, first execute:
> java DumpSer
Then execute:
> java LoadSer
What do you see?

Reason: Once a class is loaded it remains loaded and all its static fields remain set with any values assign to them. The Thumb rule is Statics's are not serialized but initialized.

1 comment:

Arun said...

True. static variables aren't serialized. Meaning that they never find any place in the "out.dmp". The reason is that the static variables are attached to the class and not the objects. But the "static variables are initialized" part confuses me. One major flaw in the example is that you are working on two different JVMs. The one for DumpSer and the one for LoadSer. And obviously the "var" variable will never initialize to the "100" value. Coz, you didnt call the set() method in the second JVM. Just try

public class DumpSer {
public static void main(String[] args) throws Exception {
Ser kk = new Ser();
kk.set();
File outFile = new File("out.dmp");
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(outFile));
out.writeObject(kk);
out.close();
File inFile = new File("out.dmp");
ObjectInputStream in = new ObjectInputStream(new FileInputStream(inFile));
Ser jj = (Ser)in.readObject();
in.close();
System.out.println("Val -> "+jj.var);

}
}

In this case, you are just playing with a single JVM. And during deserialization, you just reconstruct the Ser object. Reconstruction also means that your static variables will be initialized (Your set() method doesnt have a call there)

Tired of seeing that 500 Bad gateway error while deploying a Springboot application in AWS...?

By default, Spring Boot applications will listen on port 8080. Elastic Beanstalk assumes that the application will listen on port 5000. Th...