Java object serialization

Java serialization turns a graph of objects into bytes and back, keeping shared references and cycles intact. It is built into the JDK and still used for caches, sessions and RMI, but it has sharp edges: constructors that do not run, writes that silently repeat old state, version mismatches and real security risks with untrusted data. This page shows how it works and runs each of those cases.

Contents

How Java serialization works

A class opts in by implementing the marker interface Serializable, which has no methods. ObjectOutputStream.writeObject then walks the object graph: for each object it writes a description of its class (name, serialVersionUID and field names and types) the first time that class appears, followed by the values of the object's non-static, non-transient fields, recursing into referenced objects. Each object gets a handle number, and an object met a second time is written as a short back-reference to its handle. That is how shared references and cycles survive a round trip.

ObjectInputStream.readObject reverses the process. It creates each object without calling its constructor, the way the JVM itself can, and sets the fields directly from the stream. Most of the surprises on this page follow from that one decision: the stream, not your constructor, decides what the object contains.

The serialization mechanisms
MechanismSincePurpose
Serializable, transient, serialVersionUIDJava 1.1Opt in, skip fields, identify the class version
writeObject / readObject methodsJava 1.1Customize the format, validate on reading
ExternalizableJava 1.1Write the whole format yourself; needs a public no-argument constructor
writeReplace / readResolveJava 1.2Substitute another object, for example to keep singletons
ObjectInputFilterJava 9 (JEP 290)Allow or reject classes and limit sizes while reading
Record serializationJava 16 (JEP 395)Records are rebuilt through their canonical constructor
@Serial annotationJava 14Marks the special methods and fields so the compiler can check them
Filter factoriesJava 17 (JEP 415)Choose a filter per stream or per context

All programs below were compiled and run on JDK 21. They serialize into byte arrays, so you can run them without creating files; writing to a file is the same code with a FileOutputStream.

What gets saved and which constructors run

The program saves a User whose parent class is not serializable. The constructors print a line when they run, so you can see which ones are called on the way back.

Java
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;

public class SerializeBasics {

    // Not Serializable: its no-arg constructor runs again during deserialization
    static class Base {
        String baseNote = "set in Base()";

        Base() {
            System.out.println("  Base() constructor ran");
        }
    }

    static class User extends Base implements Serializable {
        private static final long serialVersionUID = 1L;
        static int instances = 0;

        String name;
        transient String password;        // never written to the stream
        ArrayList<String> roles = new ArrayList<>();   // a Serializable list type

        User(String name, String password) {
            this.name = name;
            this.password = password;
            instances++;
            System.out.println("  User(...) constructor ran");
        }
    }

    static byte[] serialize(Object o) throws IOException {
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        try (ObjectOutputStream out = new ObjectOutputStream(bytes)) {
            out.writeObject(o);
        }
        return bytes.toByteArray();
    }

    static Object deserialize(byte[] data) throws IOException, ClassNotFoundException {
        try (ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(data))) {
            return in.readObject();
        }
    }

    public static void main(String[] args) throws Exception {
        System.out.println("creating:");
        User u = new User("ana", "s3cret");
        u.roles.add("admin");
        u.baseNote = "changed before saving";

        byte[] data = serialize(u);
        System.out.println("serialized to " + data.length + " bytes");

        System.out.println("deserializing:");
        User copy = (User) deserialize(data);
        System.out.println("name:      " + copy.name);
        System.out.println("roles:     " + copy.roles);
        System.out.println("password:  " + copy.password + "  (transient)");
        System.out.println("baseNote:  " + copy.baseNote + "  (from the non-serializable parent)");
        System.out.println("same object? " + (copy == u) + ", instances counter: "
                + User.instances);
    }
}

Output:

Output
creating:
  Base() constructor ran
  User(...) constructor ran
serialized to 169 bytes
deserializing:
  Base() constructor ran
name:      ana
roles:     [admin]
password:  null  (transient)
baseNote:  set in Base()  (from the non-serializable parent)
same object? false, instances counter: 1
  • When deserializing, User's constructor did not run. So validation in the constructor of a serializable class is skipped for every object that comes from a stream.
  • Base() did run. For a non-serializable parent class, its no-argument constructor is called and its fields are not saved, which is why baseNote came back as "set in Base()" instead of the value set before saving. If the parent had no accessible no-argument constructor, deserialization would fail with InvalidClassException.
  • The transient field password was not written, so it came back as null. Use transient for secrets, caches and fields that can be recomputed.
  • Static fields belong to the class, not the object, and are never serialized; the counter stayed at 1.
  • The copy is a new object. The 169 bytes include the class names and field descriptions, not just the data.

The stream format, shared references and the repeated-write trap

The program first writes an empty stream to show its header. It then serializes a list in which one node appears twice and two nodes point at each other. Finally it writes one object, changes it and writes it again to the same stream, which is what a program does when it sends updates over a long-lived ObjectOutputStream.

Java
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

public class GraphAndFormat {

    static class Node implements Serializable {
        private static final long serialVersionUID = 1L;
        String name;
        Node next;                                          // allows cycles
        int value;

        Node(String name, int value) {
            this.name = name;
            this.value = value;
        }
    }

    public static void main(String[] args) throws Exception {
        // 1. The stream header
        ByteArrayOutputStream empty = new ByteArrayOutputStream();
        new ObjectOutputStream(empty).close();
        StringBuilder hex = new StringBuilder();
        for (byte b : empty.toByteArray()) {
            hex.append(String.format("%02x ", b));
        }
        System.out.println("an empty object stream: " + hex.toString().strip());

        // 2. Shared references and cycles survive
        Node a = new Node("a", 1);
        Node b = new Node("b", 2);
        a.next = b;
        b.next = a;                                         // a -> b -> a
        List<Node> list = new ArrayList<>(List.of(a, b, a)); // a appears twice
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        try (ObjectOutputStream out = new ObjectOutputStream(bytes)) {
            out.writeObject(list);
        }
        @SuppressWarnings("unchecked")
        List<Node> copy = (List<Node>) new ObjectInputStream(
                new ByteArrayInputStream(bytes.toByteArray())).readObject();
        System.out.println("list[0] == list[2]: " + (copy.get(0) == copy.get(2))
                + ", cycle kept: " + (copy.get(0).next.next == copy.get(0)));

        // 3. Writing the same object twice writes a back-reference, not the new state
        Node counter = new Node("counter", 1);
        ByteArrayOutputStream twice = new ByteArrayOutputStream();
        ObjectOutputStream out = new ObjectOutputStream(twice);
        out.writeObject(counter);
        int afterFirst = twice.size();
        counter.value = 99;                                 // change it, then write again
        out.writeObject(counter);
        out.flush();
        int afterSecond = twice.size();
        out.reset();                                        // forget objects already written
        out.writeObject(counter);
        out.close();
        ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(
                twice.toByteArray()));
        System.out.println("first write: " + afterFirst + " bytes, second write: "
                + (afterSecond - afterFirst) + " bytes");
        System.out.println("read back: " + ((Node) in.readObject()).value + ", "
                + ((Node) in.readObject()).value + ", after reset(): "
                + ((Node) in.readObject()).value);
    }
}

Output:

Output
an empty object stream: ac ed 00 05
list[0] == list[2]: true, cycle kept: true
first write: 122 bytes, second write: 5 bytes
read back: 1, 1, after reset(): 99
  • Every stream starts with the magic number ac ed and the format version 00 05. Seeing AC ED or its Base64 form rO0 in a cookie or request is a sign that a system accepts Java serialized data.
  • After the round trip, list[0] and list[2] are still the same object, and the cycle a, b, a is intact. A JSON library would write a twice, or fail on the cycle.
  • The first write took 122 bytes; the second write of the same object took 5, a 1-byte back-reference marker plus a 4-byte handle. The change to 99 was never written, so the reader got 1 both times. Only after reset(), which makes the stream forget everything already written, did the new value arrive. Long-lived streams must call reset() between messages, which also keeps the stream's handle table from growing forever.

Custom hooks: readObject, readResolve and singletons

A serializable class can declare private writeObject and readObject methods to control its fields, and readResolve to replace the object that was read. The program uses readObject to recompute a transient field and to reject an impossible value, then round-trips two singletons and an enum constant.

Java
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InvalidObjectException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serial;
import java.io.Serializable;

public class CustomHooks {

    // writeObject/readObject: control the format and validate on the way in
    static class Temperature implements Serializable {
        @Serial
        private static final long serialVersionUID = 1L;
        private double celsius;
        private transient String label;                    // derived, recomputed after reading

        Temperature(double celsius) {
            this.celsius = celsius;
            this.label = celsius + " C";
        }

        @Serial
        private void writeObject(ObjectOutputStream out) throws IOException {
            out.defaultWriteObject();
        }

        @Serial
        private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
            in.defaultReadObject();
            if (celsius < -273.15) {
                throw new InvalidObjectException("below absolute zero: " + celsius);
            }
            label = celsius + " C";
        }
    }

    // A singleton without readResolve: deserializing creates a second instance
    static class Config implements Serializable {
        @Serial
        private static final long serialVersionUID = 1L;
        static final Config INSTANCE = new Config();

        private Config() {
        }
    }

    static class SafeConfig implements Serializable {
        @Serial
        private static final long serialVersionUID = 1L;
        static final SafeConfig INSTANCE = new SafeConfig();

        private SafeConfig() {
        }

        @Serial
        private Object readResolve() {
            return INSTANCE;                                // replace the copy with the singleton
        }
    }

    enum Mode { FAST, SAFE }

    static Object roundTrip(Object o) throws Exception {
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        try (ObjectOutputStream out = new ObjectOutputStream(bytes)) {
            out.writeObject(o);
        }
        try (ObjectInputStream in = new ObjectInputStream(
                new ByteArrayInputStream(bytes.toByteArray()))) {
            return in.readObject();
        }
    }

    public static void main(String[] args) throws Exception {
        Temperature t = (Temperature) roundTrip(new Temperature(21.5));
        System.out.println("transient label recomputed in readObject: " + t.label);

        Temperature bad = new Temperature(0);
        bad.celsius = -300;                                 // a value only a forged stream has
        try {
            roundTrip(bad);
        } catch (InvalidObjectException e) {
            System.out.println("readObject validation: " + e.getMessage());
        }

        System.out.println("singleton without readResolve, same instance: "
                + (roundTrip(Config.INSTANCE) == Config.INSTANCE));
        System.out.println("singleton with readResolve, same instance:    "
                + (roundTrip(SafeConfig.INSTANCE) == SafeConfig.INSTANCE));
        System.out.println("enum constant, same instance:                 "
                + (roundTrip(Mode.SAFE) == Mode.SAFE));
    }
}

Output:

Output
transient label recomputed in readObject: 21.5 C
readObject validation: below absolute zero: -300.0
singleton without readResolve, same instance: false
singleton with readResolve, same instance:    true
enum constant, same instance:                 true
  • The transient label was recomputed in readObject after defaultReadObject() filled in the normal fields.
  • A temperature of -300 can only come from a manipulated stream, since the constructor is skipped. readObject is the place to check invariants, and it rejected the value with InvalidObjectException.
  • The plain singleton came back as a second instance: INSTANCE was no longer unique. readResolve returning INSTANCE fixed it. Enum constants are always serialized by name and resolved to the existing constant, which is why an enum is the simplest serializable singleton.
  • The @Serial annotation (Java 14) lets the compiler check these methods, because a misspelled readObject or the wrong signature would otherwise be silently ignored.

serialVersionUID and InvalidClassException

The stream records each class's serialVersionUID. When reading, the JVM compares it with the UID of the class it has loaded and refuses the data if they differ. If a class does not declare one, the JVM computes one from the class's structure, so adding a method or a field changes it, and old data can no longer be read. The program prints a declared and a computed UID, then writes an Order and changes the UID inside the byte stream from 1 to 2, exactly what a stream from another version of the class would contain.

Java
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InvalidClassException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.ObjectStreamClass;
import java.io.Serializable;
import java.nio.ByteBuffer;

public class VersionMismatch {

    static class Order implements Serializable {
        private static final long serialVersionUID = 1L;
        String item = "book";
    }

    @SuppressWarnings("serial")         // no serialVersionUID on purpose: the JVM computes one
    static class NoUid implements Serializable {
        String item = "pen";
    }

    public static void main(String[] args) throws Exception {
        System.out.println("declared UID of Order: "
                + ObjectStreamClass.lookup(Order.class).getSerialVersionUID());
        System.out.println("computed UID of NoUid: "
                + ObjectStreamClass.lookup(NoUid.class).getSerialVersionUID());

        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        try (ObjectOutputStream out = new ObjectOutputStream(bytes)) {
            out.writeObject(new Order());
        }
        byte[] data = bytes.toByteArray();

        // Simulate a stream written by a different version of Order: the 8-byte UID
        // follows the class name in the stream, so overwrite it with 2
        byte[] name = Order.class.getName().getBytes();
        int at = indexOf(data, name) + name.length;
        ByteBuffer.wrap(data, at, 8).putLong(2L);

        try (ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(data))) {
            in.readObject();
        } catch (InvalidClassException e) {
            System.out.println("InvalidClassException: " + e.getMessage());
        }
    }

    static int indexOf(byte[] data, byte[] part) {
        outer:
        for (int i = 0; i <= data.length - part.length; i++) {
            for (int j = 0; j < part.length; j++) {
                if (data[i + j] != part[j]) {
                    continue outer;
                }
            }
            return i;
        }
        throw new IllegalArgumentException("not found");
    }
}

Output:

Output
declared UID of Order: 1
computed UID of NoUid: -8159002293794623984
InvalidClassException: VersionMismatch$Order; local class incompatible: stream classdesc serialVersionUID = 2, local class serialVersionUID = 1

Always declare private static final long serialVersionUID in a serializable class, and change it only when you deliberately want old data rejected. With a fixed UID, compatible changes work: a field added to the class reads as its default value from old data, and a field missing from the class is ignored. Changing a field's type, or moving the class to another package, is incompatible whatever the UID is. The computed UID can also differ between compilers, because synthetic members created by the compiler are part of the calculation. javac warns about a missing UID with -Xlint:serial.

Deserializing safely

Reading serialized data from an untrusted source is dangerous. The stream decides which classes are instantiated, and attackers have built "gadget chains" from ordinary library classes whose readObject methods end up running code. Several well-known remote code execution vulnerabilities in application servers came from exactly this. The program shows the defenses:

  • An ObjectInputFilter checks every class before it is created. The pattern SafeDeserialization$Range;java.lang.*;!* allows the record and basic Java types and rejects everything else.
  • The same filter syntax sets limits: maxdepth, maxbytes, maxrefs and maxarray stop streams that try to exhaust memory or the stack.
  • Records are deserialized through their canonical constructor, so their validation runs. The program swaps the two numbers inside a serialized Range(1, 5) to produce an invalid range.
Java
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InvalidClassException;
import java.io.InvalidObjectException;
import java.io.ObjectInputFilter;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

public class SafeDeserialization {

    record Range(int min, int max) implements Serializable {
        Range {
            if (min > max) {
                throw new IllegalArgumentException("min " + min + " > max " + max);
            }
        }
    }

    static byte[] serialize(Object o) throws IOException {
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        try (ObjectOutputStream out = new ObjectOutputStream(bytes)) {
            out.writeObject(o);
        }
        return bytes.toByteArray();
    }

    static Object read(byte[] data, ObjectInputFilter filter) throws Exception {
        try (ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(data))) {
            if (filter != null) {
                in.setObjectInputFilter(filter);
            }
            return in.readObject();
        }
    }

    public static void main(String[] args) throws Exception {
        // An allow-list: only these classes may appear in the stream, everything else is rejected
        ObjectInputFilter allow = ObjectInputFilter.Config.createFilter(
                "SafeDeserialization$Range;java.lang.*;!*");

        System.out.println("Range allowed: " + read(serialize(new Range(1, 5)), allow));
        try {
            read(serialize(new HashMap<>(Map.of("k", "v"))), allow);
        } catch (InvalidClassException e) {
            System.out.println("HashMap rejected: " + e.getMessage());
        }

        // Limits: depth of nesting and total bytes, checked as the stream is read
        java.util.List<Object> deep = new java.util.ArrayList<>();
        java.util.List<Object> cur = deep;
        for (int i = 0; i < 50; i++) {
            java.util.List<Object> inner = new java.util.ArrayList<>();
            cur.add(inner);
            cur = inner;
        }
        ObjectInputFilter limits = ObjectInputFilter.Config.createFilter(
                "maxdepth=20;maxbytes=100000;java.util.ArrayList;!*");
        try {
            read(serialize(deep), limits);
        } catch (InvalidClassException e) {
            System.out.println("50 nested lists with maxdepth=20: " + e.getMessage());
        }

        // Records are rebuilt through their canonical constructor, so validation runs again.
        // Tamper with the stream: swap the two int values of Range(1, 5)
        byte[] data = serialize(new Range(1, 5));
        int last = data.length;
        byte[] tampered = data.clone();
        System.arraycopy(data, last - 8, tampered, last - 4, 4);
        System.arraycopy(data, last - 4, tampered, last - 8, 4);
        try {
            read(tampered, null);
        } catch (InvalidObjectException e) {
            System.out.println("tampered record: InvalidObjectException, cause: "
                    + e.getCause().getMessage());
        }
    }
}

Output:

Output
Range allowed: Range[min=1, max=5]
HashMap rejected: filter status: REJECTED
50 nested lists with maxdepth=20: filter status: REJECTED
tampered record: InvalidObjectException, cause: min 5 > max 1

The HashMap was refused before any of its code ran. The 50 nested lists exceeded maxdepth=20 and were rejected while reading. The tampered record was rejected by its own compact constructor, wrapped in an InvalidObjectException; a normal class would have accepted the swapped values. A filter can also be set for the whole JVM with the jdk.serialFilter system property, which protects libraries that deserialize internally.

Size and speed compared with a hand-written format

Serialization is convenient, but the class descriptions and per-object markers cost space and time. The program writes 100,000 small points with labels, once with serialization and once with DataOutputStream, where the code writes each field itself. Both round trips are checked for equality.

Java
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

public class SizeAndSpeed {

    record Point(int x, int y, String label) implements Serializable { }

    static class PointClass implements Serializable {
        private static final long serialVersionUID = 1L;
        int x;
        int y;
        String label;

        PointClass(int x, int y, String label) {
            this.x = x;
            this.y = y;
            this.label = label;
        }
    }

    static byte[] javaSerialize(Object o) throws IOException {
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        try (ObjectOutputStream out = new ObjectOutputStream(bytes)) {
            out.writeObject(o);
        }
        return bytes.toByteArray();
    }

    static Object javaDeserialize(byte[] data) throws Exception {
        try (ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(data))) {
            return in.readObject();
        }
    }

    static byte[] dataWrite(List<Point> points) throws IOException {
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        try (DataOutputStream out = new DataOutputStream(bytes)) {
            out.writeInt(points.size());
            for (Point p : points) {
                out.writeInt(p.x());
                out.writeInt(p.y());
                out.writeUTF(p.label());
            }
        }
        return bytes.toByteArray();
    }

    static List<Point> dataRead(byte[] data) throws IOException {
        try (DataInputStream in = new DataInputStream(new ByteArrayInputStream(data))) {
            int n = in.readInt();
            List<Point> points = new ArrayList<>(n);
            for (int i = 0; i < n; i++) {
                points.add(new Point(in.readInt(), in.readInt(), in.readUTF()));
            }
            return points;
        }
    }

    interface Job {
        Object run() throws Exception;
    }

    static long best(Job job) throws Exception {
        long best = Long.MAX_VALUE;
        for (int i = 0; i < 5; i++) {
            long start = System.nanoTime();
            job.run();
            best = Math.min(best, System.nanoTime() - start);
        }
        return best / 1000000;
    }

    public static void main(String[] args) throws Exception {
        System.out.println("one Point record: " + javaSerialize(new Point(1, 2, "p")).length
                + " bytes with ObjectOutputStream, "
                + dataWrite(List.of(new Point(1, 2, "p"))).length
                + " bytes with DataOutputStream (incl. a 4-byte count)");

        List<Point> points = new ArrayList<>();
        List<PointClass> classes = new ArrayList<>();
        for (int i = 0; i < 100000; i++) {
            points.add(new Point(i, -i, "p" + i % 100));
            classes.add(new PointClass(i, -i, "p" + i % 100));
        }
        byte[] ser = javaSerialize(new ArrayList<>(points));
        byte[] serClass = javaSerialize(new ArrayList<>(classes));
        byte[] data = dataWrite(points);
        System.out.printf("100,000 points: serialization %,d bytes (record), %,d (class), "
                + "DataOutputStream %,d bytes%n", ser.length, serClass.length, data.length);
        if (!dataRead(data).equals(points) || !javaDeserialize(ser).equals(points)) {
            throw new IllegalStateException("round trip failed");
        }

        System.out.println("best of 5 runs:");
        System.out.printf("  serialize records:   %4d ms   deserialize: %4d ms%n",
                best(() -> javaSerialize(new ArrayList<>(points))),
                best(() -> javaDeserialize(ser)));
        System.out.printf("  serialize classes:   %4d ms   deserialize: %4d ms%n",
                best(() -> javaSerialize(new ArrayList<>(classes))),
                best(() -> javaDeserialize(serClass)));
        System.out.printf("  DataOutputStream:    %4d ms   read back:   %4d ms%n",
                best(() -> dataWrite(points)), best(() -> dataRead(data)));
    }
}

Output (rough comparison on a 2-CPU Linux VM, JDK 21, best of 5; absolute times will differ on yours):

Output
one Point record: 88 bytes with ObjectOutputStream, 15 bytes with DataOutputStream (incl. a 4-byte count)
100,000 points: serialization 1,990,124 bytes (record), 1,990,129 (class), DataOutputStream 1,290,004 bytes
best of 5 runs:
  serialize records:     27 ms   deserialize:   23 ms
  serialize classes:     25 ms   deserialize:   20 ms
  DataOutputStream:       7 ms   read back:      9 ms
  • One point took 88 bytes with serialization and 15 bytes as raw fields, because the first object carries its class description. In a large list the description is written once, so the overhead per object falls, but 100,000 points still took about 50% more space than the hand-written format.
  • Records and ordinary classes were about the same size and speed here.
  • The hand-written format was roughly two to four times faster in both directions. The price is code you maintain for every field and every version.

When to use Java serialization

Choosing a serialization approach
Use caseRecommendation
Data exchanged with other systems or languagesJSON with Jackson, Protocol Buffers or Avro
Long-term storageAn explicit, versioned format, not Java serialization
Data from untrusted sourcesNever Java serialization without a strict allow-list filter
Short-lived data between JVMs running the same code (caches, sessions)Acceptable, with a declared serialVersionUID
Simple value types that must be serializableRecords, which keep constructor validation
SingletonsAn enum, or readResolve
A stream of many messagesCall reset() between messages
Compact, fast binary data under your controlDataOutputStream or ByteBuffer with your own layout

For a hand-made binary record format with random access, see the RandomAccessFile page.