A lazily created field is assigned before its setup ends, so a thread that checks it without the lock may use it unfinished
What it finds
In double-checked locking, if (cache == null) { synchronized (lock) { if (cache == null) { cache = new Cache(); cache.load(); } } } stores the object in the field before it is set up. Another thread makes the first check without the lock, sees a field that is no longer null, and goes on to use an object whose load() has not run yet, or is still running. volatile does not help here: it orders the writes made before the assignment, not the ones after it.
Reported, inside the inner check of double-checked locking on a field of this file, is an assignment of the field that is followed, in the same block, by a statement that calls a method on the object in the field or assigns one of its fields or elements. Building the object in a local variable and assigning the field as the last step publishes it complete.
From the rule's source, lazy_field_published_early.rs.
import java.util.HashMap;import java.util.Map; class Registry { private static volatile Map<String, String> table; private static volatile Map<String, String> other; private static volatile Map<String, String> third; private static final Object LOCK = new Object(); static Map<String, String> table() { if (table == null) { synchronized (LOCK) { if (table == null) { table = new HashMap<>();tx0 reports: table is published here, before its setup below is done table.put("a", "b"); } } } return table; } static Map<String, String> other() { if (other == null) { synchronized (LOCK) { if (other == null) { Map<String, String> fresh = new HashMap<>(); fresh.put("a", "b"); other = fresh; } } } return other; } static Map<String, String> third() { if (third == null) { synchronized (LOCK) { if (third == null) { third = new HashMap<>(); System.out.println("created " + third); } } } return third; }} Turn it on, off or suppress it
The rule runs from the recommended tier up. To turn it on in a lower tier, give it a level in tx0.toml:
[rules]
"tx0/java:lazy-field-published-early" = "warning"To keep one finding, suppress it with a reason. tx0 suppress ID --reason "..." writes the comment on the line before the code:
// tx0: ignore[tx0/java:lazy-field-published-early] reason="..."tx0 explain tx0/java:lazy-field-published-early shows the same in the terminal. Found a false positive? Report it.