Video in progress

Strong Middle 🧱 OOP and SOLID

Why is passing `this` out of a constructor ("this escape") dangerous?

Until the constructor finishes, the object is not fully built. If this is registered as a listener, handed to a thread or added to a static collection, other code (or another thread) can see it half-initialized, with final fields not yet written.

📖 Answer

public class PriceWatcher implements PriceListener {
    private final Map<String, BigDecimal> limits;

    public PriceWatcher(EventBus bus, Map<String, BigDecimal> limits) {
        bus.register(this);                 // this escaped
        this.limits = Map.copyOf(limits);   // not written yet
    }

    @Override public void onPrice(String sku, BigDecimal p) {
        if (p.compareTo(limits.get(sku)) > 0) alert(sku);   // may throw NPE
    }
}

If EventBus publishes an event on another thread, onPrice can be called while limits == null. There is also a subtler point: the Java Memory Model only guarantees visibility of final fields after the constructor has finished. If this escapes early, that guarantee is gone, and another thread can even see the old (default) value.

The same problem shows up with new Thread(this::loop).start() inside a constructor, or when a parent constructor calls register(this) before the child class has been initialized.

The fix is to separate creation from starting:

public static PriceWatcher start(EventBus bus, Map<String, BigDecimal> limits) {
    var w = new PriceWatcher(limits);   // fully built
    bus.register(w);                    // published afterwards
    return w;
}

In Spring this is usually solved with @PostConstruct or SmartLifecycle.start(). javac -Xlint:this-escape in JDK 21 also warns about such spots.