Skip to lesson

Serialization: common mistakes and practice

A review of this module. Skip it if you feel confident; the next module does not need it.

Fix the mistakes

The slips that cost marks in this module. Spot each one, then check the fix.

Most serialization bugs come from four mistakes: a field that cannot be saved, a transient field that comes back empty, a class changed without a declared version, and reading data the program does not control. Each section shows one mistake and its fix.

Mistake 1: a field that cannot be serialized

NotSerializableException names a class somewhere in the object graph that is not Serializable. In a game, that is often a helper or live object kept inside a saved object: a player object from a library, a sound player or a connection.

Example 1 · Mistake: a Player object inside a saved score

NestedFieldFixDemo.javaJava
import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.NotSerializableException;import java.io.ObjectOutputStream;import java.io.Serializable;import java.util.ArrayList;import java.util.List;
class Player {                                    // NOT Serializable    String name;
    Player(String name) {        this.name = name;    }}
class BrokenScore implements Serializable {       // mistake: holds a Player object    private static final long serialVersionUID = 1L;    Player player;    int points;
    BrokenScore(Player player, int points) {        this.player = player;        this.points = points;    }}
record Score(String player, int points) implements Serializable {   // fix: keep only data}
public class NestedFieldFixDemo {    static void trySave(String label, Object obj) throws IOException {        try (ObjectOutputStream out = new ObjectOutputStream(new ByteArrayOutputStream())) {            out.writeObject(obj);            System.out.println(label + ": saved");        } catch (NotSerializableException e) {            System.out.println(label + ": NotSerializableException: " + e.getMessage());        }    }
    public static void main(String[] args) throws IOException {        List<BrokenScore> broken = new ArrayList<>(List.of(new BrokenScore(new Player("Asha"), 420)));        List<Score> fixed = new ArrayList<>(List.of(new Score("Asha", 420)));
        trySave("Broken list", broken);        trySave("Fixed list", fixed);    }}
Output
Broken list: NotSerializableException: Player
Fixed list: saved

What this code does

  • BrokenScore is serializable, but its player field holds a Player, which is not, so saving the list fails with the message Player.
  • The fixed Score record keeps only the data it needs, the player's name as a String, so the list saves.

The fix depends on the field. If it is data, make its class serializable, or store only the data (a name instead of a Player object). If it is a helper, mark it transient and create it again after loading.

Mistake 2: transient fields that come back empty

A transient field is 0, false or null after loading, because neither its initializer nor the constructor runs. Code that uses a transient cache straight away then throws NullPointerException or gives wrong answers.

Example 2 · Fix: a transient rank cache rebuilt lazily

TransientRankDemo.javaJava
import java.io.ByteArrayInputStream;import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.ObjectInputStream;import java.io.ObjectOutputStream;import java.io.Serializable;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;
class Leaderboard implements Serializable {    private static final long serialVersionUID = 1L;    List<String> namesInOrder = new ArrayList<>();    private transient Map<String, Integer> rankOf;       // cache, rebuilt when needed
    void add(String name) {        namesInOrder.add(name);        rankOf = null;                                    // cache is out of date    }
    int rank(String name) {        if (rankOf == null) {                             // also true right after loading            rankOf = new HashMap<>();            for (int i = 0; i < namesInOrder.size(); i++) {                rankOf.put(namesInOrder.get(i), i + 1);            }        }        return rankOf.getOrDefault(name, -1);    }}
public class TransientRankDemo {    public static void main(String[] args) throws IOException, ClassNotFoundException {        Leaderboard board = new Leaderboard();        board.add("Asha");        board.add("Bilal");        board.add("Chitra");        System.out.println("Before saving, Bilal is rank " + board.rank("Bilal"));
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();        try (ObjectOutputStream out = new ObjectOutputStream(buffer)) {            out.writeObject(board);        }        try (ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(buffer.toByteArray()))) {            Leaderboard back = (Leaderboard) in.readObject();            System.out.println("After loading, Chitra is rank " + back.rank("Chitra"));            System.out.println("Unknown player: " + back.rank("Dev"));        }    }}
Output
Before saving, Bilal is rank 2
After loading, Chitra is rank 3
Unknown player: -1

What this code does

  • rankOf is a transient cache, so it is null after loading. rank() rebuilds it whenever it is null.
  • add sets the cache to null too, so the same code also handles changes before saving.

Every transient field needs a plan: rebuild it in a private readObject after defaultReadObject(), or build it lazily in a getter that checks for null. Also remember that static fields are never saved.

Mistake 3: changing a class without a declared version

Without serialVersionUID, adding one field changes the computed version, and every saved file fails with InvalidClassException. Players lose their progress after an update.

Example 3 · Fix: a declared version keeps old saves working

DeclaredVersionKeepsDataDemo.javaJava
import java.io.ByteArrayInputStream;import java.io.IOException;import java.io.ObjectInputStream;import java.io.Serial;import java.io.Serializable;import java.util.Base64;
class Student implements Serializable {    @Serial    private static final long serialVersionUID = 1L;    String name;    int roll;    int level;              // new; old data gives 0
    @Serial    private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {        in.defaultReadObject();        if (level == 0) {            level = 1;      // sensible value for old data        }    }}
public class DeclaredVersionKeepsDataDemo {    // Saved by version 1 (serialVersionUID 1L, name and roll)    static final String SAVED_BY_V1 =            "rO0ABXNyAAdTdHVkZW50AAAAAAAAAAECAAJJAARyb2xsTAAEbmFtZXQAEkxqYXZhL2xhbmcvU3RyaW5nO3hwAAAADHQABVByaXlh";
    public static void main(String[] args) throws IOException, ClassNotFoundException {        byte[] bytes = Base64.getDecoder().decode(SAVED_BY_V1);        try (ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bytes))) {            Student s = (Student) in.readObject();            System.out.println(s.name + ", roll " + s.roll + ", level " + s.level);        }    }}
Output
Priya, roll 12, level 1

What this code does

  • The saved data comes from version 1 with serialVersionUID = 1L. Version 2 keeps 1L and adds level, so the old save still loads.
  • readObject turns the missing level (0) into 1, a sensible value for old players.

Declare private static final long serialVersionUID = 1L; from the first release and keep it for compatible changes. New fields then load as defaults, and readObject (or a record's compact constructor) can turn those defaults into sensible values.

Mistake 4: reading data you do not control

Calling readObject on uploaded files or network data is the most serious mistake: the bytes choose which classes run. For your own files, add an allow-list ObjectInputFilter with limits, and validate values with a record or a checking readObject.

Example 4 · Fix: move a saved score list to CSV once

ScoresToCsvDemo.javaJava
import java.io.IOException;import java.io.ObjectInputFilter;import java.io.ObjectInputStream;import java.io.ObjectOutputStream;import java.io.Serializable;import java.nio.charset.StandardCharsets;import java.nio.file.Files;import java.nio.file.Path;import java.util.ArrayList;import java.util.List;
record Score(String player, int points) implements Serializable {    Score {        if (points < 0) {            throw new IllegalArgumentException("points cannot be negative");        }    }}
public class ScoresToCsvDemo {    public static void main(String[] args) throws IOException, ClassNotFoundException {        Path ser = Path.of("scores.ser");        Path csv = Path.of("scores.csv");
        // The old version of the game saved this file        try (ObjectOutputStream out = new ObjectOutputStream(Files.newOutputStream(ser))) {            out.writeObject(new ArrayList<>(List.of(new Score("Asha", 420), new Score("Bilal", 385))));        }
        // One-time migration: read our own file through an allow-list, write CSV        List<String> lines = new ArrayList<>();        lines.add("player,points");        try (ObjectInputStream in = new ObjectInputStream(Files.newInputStream(ser))) {            in.setObjectInputFilter(ObjectInputFilter.Config.createFilter(                    "maxdepth=5;Score;java.util.ArrayList;java.lang.*;!*"));            for (Object o : (List<?>) in.readObject()) {                Score s = (Score) o;                lines.add(s.player() + "," + s.points());            }        }        Files.write(csv, lines, StandardCharsets.UTF_8);        Files.delete(ser);                                // the new version uses only the CSV
        System.out.println("scores.csv:");        for (String line : Files.readAllLines(csv, StandardCharsets.UTF_8)) {            System.out.println("  " + line);        }        Files.delete(csv);    }}
Output
scores.csv:
  player,points
  Asha,420
  Bilal,385

What this code does

  • The old file is the game's own, so reading it once through an allow-list filter is acceptable.
  • Each Score becomes a player,points line under a header, and the .ser file is deleted after the migration.
  • From now on the game reads only the CSV, which people and other tools can read too.

For anything that crosses a trust boundary, or must last for years, move to a text format. A one-time migration reads the old file once through a filter and writes CSV; from then on the program reads only the CSV.

Finish up

Mark complete & continue

Next: Checked or unchecked for your own exceptions