A field is initialized lazily with a check outside the lock, but is not volatile

tx0/java:unsafe-lazy-initdefaultwarningbug, concurrency

What it finds

if (instance == null) { synchronized (lock) { if (instance == null) { instance = new Service(); } } } on a field that is not volatile can hand a half-built object to another thread: without volatile, the write of the reference may become visible before the writes made by the constructor, and the first check, made without the lock, sees it.

Reported when both checks compare the same field of this file with null, the inner one assigns it, and the field is not volatile.

From the rule's source, unsafe_lazy_init.rs.

Example from the rule's tests
class Holder {  private static Holder instance;  private static volatile Holder safe;  private Object other;   static Holder get() {    if (instance == null) {tx0 reports: instance is checked outside the lock but is not volatile      synchronized (Holder.class) {        if (instance == null) {          instance = new Holder();        }      }    }    return instance;  }   static Holder getSafe() {    if (safe == null) {      synchronized (Holder.class) {        if (safe == null) {          safe = new Holder();        }      }    }    return safe;  }   synchronized Object other() {    if (other == null) {      other = new Object();    }    return other;  }}
Highlighted lines are the ones tx0 reports, with its message under each; the other lines are left alone.

Turn it on, off or suppress it

The rule runs in every tier. To turn it off for a project, set its level in tx0.toml:

tx0.toml
[rules]
"tx0/java:unsafe-lazy-init" = "off"

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:unsafe-lazy-init] reason="..."

tx0 explain tx0/java:unsafe-lazy-init shows the same in the terminal. Found a false positive? Report it.