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 What gets saved and which constructors run The stream format, shared references and the repeated-write trap Custom hooks: readObject, readResolve and singletons serialVersionUID and InvalidClassException Deserializing safely Size and speed compared with a hand-written format When to use Java serialization
How Java serialization works
A class opts in by implementing the marker interface SerializableObjectOutputStream.writeObjectserialVersionUID
ObjectInputStream.readObject
| Mechanism | Since | Purpose |
|---|---|---|
SerializabletransientserialVersionUID | Java 1.1 | Opt in, skip fields, identify the class version |
writeObjectreadObject | Java 1.1 | Customize the format, validate on reading |
Externalizable | Java 1.1 | Write the whole format yourself; needs a public no-argument constructor |
writeReplacereadResolve | Java 1.2 | Substitute another object, for example to keep singletons |
ObjectInputFilter | Java 9 (JEP 290) | Allow or reject classes and limit sizes while reading |
| Record serialization | Java 16 (JEP 395) | Records are rebuilt through their canonical constructor |
@Serial | Java 14 | Marks the special methods and fields so the compiler can check them |
| Filter factories | Java 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
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:
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,
's constructor did not run. So validation in the constructor of a serializable class is skipped for every object that comes from a stream.User did run. For a non-serializable parent class, its no-argument constructor is called and its fields are not saved, which is whyBase() 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 withbaseNote .InvalidClassException- The
fieldtransient was not written, so it came back aspassword . Usenull for secrets, caches and fields that can be recomputed.transient - 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
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:
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
and the format versionac ed . Seeing00 05 or its Base64 formAC ED in a cookie or request is a sign that a system accepts Java serialized data.rO0 - After the round trip,
andlist[0] are still the same object, and the cycle a, b, a is intact. A JSON library would writelist[2] twice, or fail on the cycle.a - 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
, which makes the stream forget everything already written, did the new value arrive. Long-lived streams must callreset() between messages, which also keeps the stream's handle table from growing forever.reset()
Custom hooks: readObject, readResolve and singletons
A serializable class can declare private writeObjectreadObjectreadResolvereadObject
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:
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
was recomputed inlabel afterreadObject filled in the normal fields.defaultReadObject() - A temperature of -300 can only come from a manipulated stream, since the constructor is skipped.
is the place to check invariants, and it rejected the value withreadObject .InvalidObjectException - The plain singleton came back as a second instance:
was no longer unique.INSTANCE returningreadResolve 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.INSTANCE - The
annotation (Java 14) lets the compiler check these methods, because a misspelled@Serial or the wrong signature would otherwise be silently ignored.readObject
serialVersionUID and InvalidClassException
The stream records each class's serialVersionUIDOrder
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:
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-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
- An
checks every class before it is created. The patternObjectInputFilter allows the record and basic Java types and rejects everything else.SafeDeserialization$Range;java.lang.*;!* - The same filter syntax sets limits:
,maxdepth ,maxbytes andmaxrefs stop streams that try to exhaust memory or the stack.maxarray - Records are deserialized through their canonical constructor, so their validation runs. The program swaps the two numbers inside a serialized
to produce an invalid range.Range(1, 5)
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:
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 HashMapmaxdepth=20InvalidObjectExceptionjdk.serialFilter
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
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):
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
| Use case | Recommendation |
|---|---|
| Data exchanged with other systems or languages | JSON with |
| Long-term storage | An explicit, versioned format, not Java serialization |
| Data from untrusted sources | Never 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 serializable | Records, which keep constructor validation |
| Singletons | An enum, or readResolve |
| A stream of many messages | Call reset() |
| Compact, fast binary data under your control | DataOutputStreamByteBuffer |
For a hand-made binary record format with random access, see the