Skip to main content

Serialization and deserialization in java with examples

Mastering Java Serialization and Deserialization: A Production-Grade Guide

Memory in a running Java Virtual Machine (JVM) is volatile. When an application terminates, all objects residing in the heap are permanently lost. Enterprise architectures frequently require object states to persist beyond the lifecycle of a single process—whether for writing state to a disk, caching payloads in distributed memory grids like Redis, or transmitting domain models across a network socket to another service.

Pick a language, then press Listen.

Hardware and network layers do not understand high-level object graphs, method pointers, or object references. They process raw sequences of bits and bytes. Java Serialization is the built-in mechanism that converts an in-memory object graph into a stream of bytes. Conversely, Deserialization reconstructs an exact functional replica of that object graph from an incoming byte stream.

This technical guide details the mechanics of Java serialization, covers the Serializable contract, analyzes advanced edge cases, and provides production-ready code examples.

Core Mechanics: The Serialization Workflow

Java Serialization & Deserialization Workflow Java Serialization & Deserialization Workflow 1 Implement Serializable Target class and non-transient members implement Serializable. 2 ObjectOutputStream Convert in-memory object graph into a stream of bytes. 3 Transmit or Store Persist byte stream to disk or transmit across a network. 4 ObjectInputStream Read incoming byte stream using readObject() method. 5 State Recovery Reconstruct exact functional replica of the object graph.
Figure: Java Serialization & Deserialization Workflow

To persist an object in Java, its class and all of its non-transient member classes must implement the java.io.Serializable interface. This interface acts as a marker interface containing zero methods or fields. It serves solely to inform the JVM that the developer explicitly authorizes the class to undergo object conversion.

The serialization and deserialization processes rely on two primary high-level I/O streams from the java.io package:

  • ObjectOutputStream: Converts Java objects into byte streams using the writeObject(Object obj) method.
  • ObjectInputStream: Reads byte streams and reconstructs Java objects using the readObject() method.

For related persistence strategies in enterprise stacks, developers often pair file storage mechanisms with containerization workflows, such as Dockerizing a Spring Boot Application with MySQL, to manage externalized state.

Step-by-Step Implementation Example

The following example builds a complete serialization pipeline using a domain model, a serialization utility, and a runner class to verify state recovery.

1. The Serializable Domain Model

Create a standard Plain Old Java Object (POJO) that implements Serializable. We explicitly declare a serialVersionUID to maintain version compatibility across JVM deployments.

package com.javatbrains.serialization;

import java.io.Serializable;

public class Car implements Serializable {
    private static final long serialVersionUID = -7617174890882744651L;

    private int number;
    private String name;
    private double cost;

    public Car(int number, String name, double cost) {
        this.number = number;
        this.name = name;
        this.cost = cost;
    }

    public int getNumber() {
        return number;
    }

    public void setNumber(int number) {
        this.number = number;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public double getCost() {
        return cost;
    }

    public void setCost(double cost) {
        this.cost = cost;
    }

    @Override
    public String toString() {
        return "Car [number=" + number + ", name=" + name + ", cost=" + cost + "]";
    }
}

2. The Serialization and Deserialization Utility

Next, implement a utility class that writes the Car instance to a local file system path and reads it back into memory.

package com.javatbrains.serialization;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class SerializationDemo {

    public static void serializeObject(Car car, String filePath) {
        try (FileOutputStream fileOut = new FileOutputStream(filePath);
             ObjectOutputStream out = new ObjectOutputStream(fileOut)) {
            out.writeObject(car);
            System.out.println("Object serialized successfully. Saved to: " + filePath);
        } catch (IOException e) {
            System.err.println("Serialization failed: " + e.getMessage());
            e.printStackTrace();
        }
    }

    public static Car deserializeObject(String filePath) {
        try (FileInputStream fileIn = new FileInputStream(filePath);
             ObjectInputStream in = new ObjectInputStream(fileIn)) {
            Car car = (Car) in.readObject();
            System.out.println("Object deserialized successfully from: " + filePath);
            return car;
        } catch (IOException | ClassNotFoundException e) {
            System.err.println("Deserialization failed: " + e.getMessage());
            e.printStackTrace();
            return null;
        }
    }

    public static void main(String[] args) {
        String filePath = "car.ser";
        
        Car originalCar = new Car(402, "Tesla Model S", 79999.00);
        
        // Execute Serialization
        serializeObject(originalCar, filePath);
        
        // Execute Deserialization
        Car recoveredCar = deserializeObject(filePath);
        
        if (recoveredCar != null) {
            System.out.println("Recovered Object Details: " + recoveredCar);
        }
    }
}

Understanding serialVersionUID

The serialVersionUID is a 64-bit hash identifier used during deserialization to verify that the sender and receiver of a serialized object have loaded classes that are compatible with respect to serialization.

If a developer modifies a class (such as adding a field or deleting a method) without explicitly declaring a serialVersionUID, the Java runtime automatically computes a hash based on various aspects of the class structure. If the receiving JVM attempts to deserialize an object using a dynamically generated ID that does not match the class definition currently in memory, the JVM throws an InvalidClassException.

For modern projects handling complex data structures without boilerplate code, consider adopting newer language features such as those detailed in Java 17 Records and Pattern Matching with Examples.

Comparison: Standard Serialization vs. Externalization

Java provides two primary interfaces for object persistence. Understanding their performance and control profiles is critical for enterprise system design.

Feature java.io.Serializable java.io.Externalizable
Implementation Effort Low. Requires implementing a marker interface. High. Requires implementing writeExternal() and readExternal().
Customization Automatic process. Uses default JVM reflection unless overridden via custom writeObject/readObject methods. Full manual control over every byte written to and read from the stream.
Performance Slower. Reflection overhead impacts throughput. Faster and leaner. Skips metadata and reflection overhead entirely.
Constructor Execution Does not invoke the constructor during deserialization. Requires a public no-arg constructor to instantiate the object before reading state.

Production Edge Cases and Best Practices

Relying solely on default serialization logic in production can lead to unexpected security vulnerabilities and data corruption. Consider the following scenarios:

1. Handling Sensitive Data with the transient Keyword

Not all fields within an object graph should be persisted. For example, database passwords, cryptographic keys, or session tokens must never be written to disk. Mark these fields with the transient keyword to instruct the JVM to skip them during serialization.

public class UserSession implements Serializable {
    private static final long serialVersionUID = 1L;
    
    private String username;
    private transient String passwordHash; // Will not be serialized
    
    // Getters and setters omitted for brevity
}

2. Object Graph References and Circular Dependencies

The ObjectOutputStream tracks every object it serializes to prevent infinite loops caused by circular references (e.g., Object A references Object B, which references Object A). The stream assigns handles to objects. If an object is referenced multiple times within the same object graph, subsequent references point to the existing handle rather than duplicating the byte stream.

3. Security Vulnerabilities in Deserialization

Accepting untrusted byte streams from external networks or clients introduces severe remote code execution (RCE) vulnerabilities. Malicious payloads can manipulate bytecode streams to execute arbitrary commands during the readObject() phase. Enterprise applications must implement strict filtering using custom ObjectInputStream implementations that override resolveClass() to whitelist permitted classes, or migrate to safe data interchange formats such as JSON or Protocol Buffers where applicable.

Troubleshooting Common Exceptions

When developing serialization routines, developers frequently encounter specific runtime errors:

  • NotSerializableException: Thrown when an object graph contains a reference to a class that does not implement Serializable. Verify that every nested object, collection element, and inherited field implements the interface or is marked transient.
  • InvalidClassException: Occurs when the serialVersionUID of the class file on the reading end does not match the incoming byte stream. Always declare a static final serialVersionUID explicitly in all persistent classes.
  • OptionalDataException: Indicates that primitive data was written to the stream where an object was expected, or vice versa. Ensure consistent stream reading and writing routines.

For legacy enterprise applications relying on database connection pools and container managed resources, ensure that state is properly handled before persistence, as referenced in JNDI configuration for Tomcat 9 with Oracle.

Summary

  • Serialization converts in-memory Java objects into byte streams, while deserialization reverses the process to reconstruct the object graph.
  • The target class must implement the java.io.Serializable marker interface to participate in default serialization.
  • Always declare an explicit serialVersionUID to prevent unexpected InvalidClassException errors during schema evolution.
  • Use the transient modifier to protect sensitive fields or non-serializable resource references from being written to disk or network streams.
  • Guard enterprise applications against untrusted deserialization vulnerabilities by validating input streams and whitelisting permitted domain classes.

Comments

Popular posts from this blog

JVM, JRE and JDK in Java

Understanding JVM, JRE, and JDK in Java Every Java developer encounters three fundamental acronyms on their first day: JVM , JRE , and JDK . Misunderstanding these foundational components leads to runtime exceptions, deployment failures, and incorrect build environments. This guide breaks down the precise architectural boundaries, memory structures, and deployment requirements of each component. ▶ Listen English (India) English (US) Hindi Telugu Tamil Kannada Malayalam Bengali Marathi Gujarati Punjabi Urdu Arabic Spanish French German Portuguese Japanese Korean Chinese (Simplified) Pick a language, then press Listen. The core problem this guide solves is ambiguous environment configuration. Developers often attempt to run production applications using a Development Kit when a Runtime Environment suffices, or they deploy platform-incompatible binaries to minimal Li...

Prime, Fibonacci and Factorial number with example in java

Mastering Prime, Fibonacci, and Factorial Algorithms in Java Prime Number Validation Workflow Prime Number Validation Workflow 1 Boundary Check Verify if the input number is less than or equal to 1. 2 Even Number Check Check if divisible by 2 and return true only if number is 2. 3 Square Root Limit Calculate integer square root as the upper loop bound. 4 Odd Factor Loop Iterate through odd integers up to limit checking divisibility. Figure: Prime Number Validation Workflow Technical coding interviews frequently test foundational algorithmic competence through three classic mathematical problems: identifying prime numbers, generating Fibonacci sequences, and calculating factorials. While these concepts originate in basic arithmetic, writing production-grade Java code to solve them requires careful attention to time complexity, memory allocation, boundary conditions, and overflow behavior. This tutorial provides rigorous, optimized Java i...

How to insert images into database using JDBC?

How to Insert Images into a Database Using JDBC Storing binary data such as images, PDFs, and application assets is a frequent requirement in enterprise software engineering. While relational databases like MySQL are optimized for structured tabular text and numeric data, they also provide robust binary storage types—specifically BLOB (Binary Large Object) variants—to handle arbitrary byte streams. When interacting with relational stores through Java, the Java Database Connectivity (JDBC) API serves as the primary bridge. ▶ Listen English (India) English (US) Hindi Telugu Tamil Kannada Malayalam Bengali Marathi Gujarati Punjabi Urdu Arabic Spanish French German Portuguese Japanese Korean Chinese (Simplified) Pick a language, then press Listen. This technical guide demonstrates how to persist image files from a local file system directly into a MySQL database usin...