readObject must not be synchronized

ID

java.readobject_must_not_be_synchronized

Severity

low

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Reliability

Language

Java

Tags

CWE:662, concurrency, reliability

Description

Reports readObject(ObjectInputStream) methods that are declared synchronized.

Rationale

During deserialization the object is not yet fully constructed and is not shared with other threads. Synchronizing readObject is therefore meaningless and gives a false sense of thread safety. If the deserialized object needs to be thread-safe, apply synchronization to the public API methods that will be called after the object is fully constructed.

// Bad - synchronized is meaningless here
private synchronized void readObject(ObjectInputStream in) throws IOException {
    in.defaultReadObject();
}

Remediation

Remove the synchronized modifier from readObject.

// Good
private void readObject(ObjectInputStream in) throws IOException {
    in.defaultReadObject();
}