...
This compliant solution protects against race-conditions by synchronizing the methodon a private lock object (see LCK00-J. Use private final lock objects to synchronize classes that may interact with untrusted code). It also protects against multiple initialization through the use of a boolean flag that is set after the instance fields have been populated.
Code Block | ||
---|---|---|
| ||
public synchronizedprivate final Object lock = new Object(); public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { synchronized (lock) { if (!initialized) { // Read instance fields this.name = (String)in.readObject(); this.UID = in.readInt(); //... initialized = true; } else { throw new IllegalStateException(); } } } |
Note that this compliant solution is insufficient to protect sensitive data.
...