A constructor hands this to other code before the object is fully built

tx0/java:this-leaked-during-constructionstrictwarningmaintainability/designdepth fastsmell

What it finds

Code that receives this from a constructor can call the object before its fields are set, and another thread can see it half built. Registering the object after construction, in a factory method, avoids both.

Reported is this passed as an argument to a method or constructor, or stored in a static field, inside a constructor.

From the rule's source, this_escapes_constructor.rs.

Example from the rule's tests
import java.util.List; class Listener {  static Listener last;  Listener(List<Listener> all) {    all.add(this);tx0 reports: leaves the constructor    last = this;tx0 reports: leaves the constructor    this.init();  }  Listener() {    this(null);  }  void init() {}}
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 from the strict tier up. To turn it on in a lower tier, give it a level in tx0.toml:

tx0.toml
[rules]
"tx0/java:this-leaked-during-construction" = "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:this-leaked-during-construction] reason="..."

tx0 explain tx0/java:this-leaked-during-construction shows the same in the terminal. Found a false positive? Report it.