Serialization in Java
Serialization in Java is a mechanism of converting the state of an object into a byte stream. This byte stream can be persisted into a file, transferred over a network, or stored in a database. The reverse process of recreating an object from the byte stream is known as Deserialization.
✨ Why Serialization?
- To save the state of an object for later use (Persistence).
- To send objects between JVMs (Distributed applications, RMI, Messaging).
- To cache data temporarily.
- To store objects in databases or files.
⚙️ How Serialization Works
Serialization is implemented using the java.io.Serializable interface.
This is a marker interface (does not contain methods) that signals the JVM that the class can be serialized.
Basic Example:
import java.io.*;
class Student implements Serializable {
int id;
String name;
Student(int id, String name) {
this.id = id;
this.name = name;
}
}
public class SerializationDemo {
public static void main(String[] args) throws Exception {
Student s1 = new Student(101, "John Doe");
// Serialization
FileOutputStream fos = new FileOutputStream("student.ser");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(s1);
oos.close();
fos.close();
System.out.println("Object has been serialized");
// Deserialization
FileInputStream fis = new FileInputStream("student.ser");
ObjectInputStream ois = new ObjectInputStream(fis);
Student s2 = (Student) ois.readObject();
ois.close();
fis.close();
System.out.println("Deserialized Student: " + s2.id + ", " + s2.name);
}
}
🔑 Important Keywords in Serialization
1. Transient Variables
A variable declared with the transient keyword is not serialized.
During deserialization, it will be initialized with its default value (0 for int, null for objects, false for boolean).
class Employee implements Serializable {
String name;
transient String password; // will not be serialized
Employee(String name, String password) {
this.name = name;
this.password = password;
}
}
2. Static Variables
Static variables are not serialized because they belong to the class, not an instance. During deserialization, they are initialized with the class value at runtime.
3. Final Variables
Final variables are included in serialization as their values. Declaring a final variable as transient is meaningless.
4. Transient vs Volatile
- Transient: Excludes a field from serialization.
- Volatile: Ensures threads read the most updated value (but does not affect serialization).
🆔 serialVersionUID
Every Serializable class has a unique identifier called serialVersionUID.
It is used during deserialization to verify that the sender and receiver of a serialized object are compatible.
If not declared manually, JVM generates one automatically (but may change if class structure changes).
class Student implements Serializable {
private static final long serialVersionUID = 1L;
int id;
String name;
}
Best Practice: Always declare serialVersionUID explicitly to avoid InvalidClassException.
📝 Custom Serialization
Sometimes we want more control over what gets serialized.
We can override writeObject() and readObject() methods.
class Account implements Serializable {
String username;
transient String password;
private void writeObject(ObjectOutputStream oos) throws Exception {
oos.defaultWriteObject();
// custom encryption
oos.writeObject("ENCRYPTED_" + password);
}
private void readObject(ObjectInputStream ois) throws Exception {
ois.defaultReadObject();
String encryptedPwd = (String) ois.readObject();
password = encryptedPwd.replace("ENCRYPTED_", "");
}
}
📦 Externalizable Interface
The Externalizable interface (extends Serializable) provides complete control over serialization.
It has two methods: writeExternal() and readExternal().
import java.io.*;
class Person implements Externalizable {
String name;
int age;
public Person() {} // mandatory no-arg constructor
public void writeExternal(ObjectOutput out) throws IOException {
out.writeObject(name);
out.writeInt(age);
}
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
name = (String) in.readObject();
age = in.readInt();
}
}
This is useful when we want performance optimization or need to exclude/include fields manually.
✅ Advantages of Serialization
- Object persistence (store objects in files or DBs).
- Easy transfer of objects between JVMs.
- Used in RMI, caching frameworks, HTTP session replication, etc.
⚠️ Limitations
- Not all objects can be serialized (e.g.,
Thread,Socket). - Serialization can affect performance if objects are large.
- Version mismatch may cause
InvalidClassException.
📌 Real-World Use Cases
- Saving game state.
- Distributed systems (RMI, RPC, Messaging queues).
- Caching frequently used objects.
- Storing user sessions in web applications.
Comments
Post a Comment