Scrivio Interview library
DebuggingIntermediate6 min read · updated 12 November 2026

An object is registered as a listener in its own constructor with bus.register(this). Another thread occasionally sees it with null fields. What is happening?

bus.register(this) hands a reference to the object to other threads before its constructor has finished, so an event delivered on another thread can call the listener while its fields are still unassigned, or while their values are not yet visible to that thread. Even final fields lose their safe-publication guarantee when this escapes during construction. The fix is to construct the object completely first and register it afterwards, typically from a static factory method.

Why this question is asked

Bugs that happen occasionally, on another thread, with null fields, are some of the most expensive to chase, because they rarely reproduce on a laptop. This one is common in event-driven code, GUI code and anything with listeners or callbacks, and it often hides inside a single innocent-looking line. Interviewers ask it to see whether we understand both halves: the order of construction and the Java Memory Model's rules on visibility. In this answer, we will recap what it means for this to escape, reproduce the race, explain why even final fields do not save us, fix it with a factory, and look at the less obvious ways this escapes through inner classes and lambdas.

1A Quick Recap: What It Means for this to Escape

While a constructor runs, the object exists but is not finished. Fields are filled in one by one, and until the constructor returns, some of them still hold null or 0. Normally nobody else can see the object during that time, because the reference only reaches the caller when new returns.

The reference escapes when the constructor itself gives this to someone else: registers it with a bus, puts it in a static map, starts a thread with it, or passes it to another object's method. From that moment, other code can call the half-built object. If that other code runs on a different thread, nothing makes it wait until construction is over.

2Reproducing the Race

Here is the shape of the bug. The listener registers itself, and only then assigns its fields.

Java
class PriceListener implements Listener {
private final Map<String, BigDecimal> prices;
private final Clock clock;
PriceListener(EventBus bus, Clock clock) {
bus.register(this); // this escapes here
this.prices = new ConcurrentHashMap<>();
this.clock = clock;
}
@Override
public void onEvent(PriceEvent e) {
prices.put(e.symbol(), e.price()); // NullPointerException: prices is null
}
}
// main thread: new PriceListener(bus, clock)
// bus thread: delivers a PriceEvent a few microseconds later
// result: usually fine, sometimes NullPointerException in onEvent
Step throughAn event arrives while the listener is still being built
Main threadPriceListenerEventBusBus thread
new PriceListener(bus, clock)
register(this): reference now shared
next event: look up listeners
onEvent(e)
prices is still null: NullPointerException
constructor assigns prices and clock
constructor returns

7 messages in order. Play them, or step through them one at a time.

The bus thread reached the object through register(this) before the constructor finished.

Notice that the problem is not only the order of the lines. Moving bus.register(this) to the last line of the constructor makes the window much smaller, but it does not make the code correct, as the next section shows. Also notice why it is occasional: the event has to arrive in the short window between register and the end of construction, which depends on load and timing.

3Why Final Fields Do Not Protect Us

Java does make a strong promise about final fields: if an object is constructed properly, any thread that sees a reference to it also sees its final fields with their constructed values, even with no locking. This is what makes immutable objects safe to share freely.

But the promise has a condition, and constructed properly means that this did not escape during construction. The JVM may let the writes to the fields become visible to other threads later than the write that makes the reference visible, and the final field rule only orders them for references obtained after the constructor finished. A reference taken from register(this) is obtained before. So even with register as the last line, a bus thread may see the reference and still read a stale null from a final field. It is rare on x86 hardware, more likely on ARM servers, and either way it is allowed by the Java Memory Model.

4The Fix: Construct Fully, Then Register

The robust fix is to separate building the object from publishing it. A private constructor only assigns fields, and a static factory method creates the object and registers it once the constructor has returned.

Java
class PriceListener implements Listener {
private final Map<String, BigDecimal> prices;
private final Clock clock;
private PriceListener(Clock clock) {
this.prices = new ConcurrentHashMap<>();
this.clock = clock;
}
static PriceListener createAndRegister(EventBus bus, Clock clock) {
PriceListener l = new PriceListener(clock); // fully constructed, final fields frozen
bus.register(l); // safe: published after construction
return l;
}
}

Two things now make it safe. The object is complete before anyone else sees it, and the final field guarantee applies, because the reference was not shared during construction. In addition, a well-written event bus stores listeners in a thread-safe collection, and putting the listener in it and reading it out on the bus thread is itself a safe publication.

In a Spring application we usually go one step further and let the container do it: the listener is a bean, and registration happens in a @PostConstruct method, from a SmartLifecycle start(), or through Spring's own @EventListener mechanism, all of which run after construction and injection.

5Inner Classes and Lambdas Leak this Too

The escape is not always as visible as register(this). An anonymous class or a lambda created in a constructor that uses instance members captures this, and handing it out leaks the half-built object just the same.

Java
PriceListener(EventBus bus, Clock clock) {
bus.subscribe(e -> prices.put(e.symbol(), e.price())); // the lambda captures this
executor.submit(this::warmUp); // a method reference to this, same problem
this.prices = new ConcurrentHashMap<>();
this.clock = clock;
}

The lambda reads the prices field, so the compiler makes it capture this, and the bus can now reach the unfinished object. Starting a thread from a constructor is the same pattern in another form. The rule is general: a constructor should not hand this, or anything that captures this, to code that may run before it returns. Since JDK 21, javac's -Xlint:this-escape warning finds many of these cases at compile time.

6Follow-up questions

Would making the fields volatile fix it?

It would fix the visibility half, because a volatile write before the reference is shared is visible to a thread that later reads that volatile. It does not fix the ordering half: an event that arrives before the fields are assigned still sees null. Constructing first and registering afterwards fixes both, so volatile is the wrong tool here.

Is it safe if the bus delivers events on the same thread?

It removes the memory visibility problem but not the ordering one. If register triggers synchronous delivery of a pending event, onEvent still runs before the fields are set, on the same thread. The factory approach is safe in both cases.

How would you find this in a large codebase?

Search constructors for this passed as an argument, for lambdas or anonymous classes created there, and for threads started there. javac's this-escape lint, SpotBugs and Sonar rules for leaking this in constructors automate most of it.

7Conclusion

In this answer, we saw that bus.register(this) lets another thread call the listener before its constructor has finished, so it can see unassigned fields, and that the Java Memory Model's final field guarantee does not apply when this escapes during construction. The fix is to construct the object completely and then publish it, with a static factory or with the container's lifecycle callbacks, and to watch for the quieter escapes through lambdas, inner classes and threads started in constructors.

What to say in the interviewAbout 80 seconds aloud

Open with

The constructor is letting this escape. register(this) hands the reference to the bus while the constructor is still running, and the bus thread can deliver an event right away, so onEvent runs on an object whose fields are still null or zero.

Then, if they want more

Moving the call to the end of the constructor shrinks the window but is still not correct, because of the memory model. The guarantee that other threads see final fields correctly without synchronization only holds if this did not escape during construction.

A reference obtained through register is obtained before the constructor ends, so the bus thread can see the reference and still read stale values, even from final fields. That is why it is occasional and timing dependent.

The fix I would use is to separate construction from publication: a private constructor that only assigns fields, and a static factory that creates the object and then registers it. In Spring I would let the container do it, with a PostConstruct method, a lifecycle bean or EventListener.

I would also check for the quieter versions, such as lambdas or anonymous classes created in the constructor that capture this, or threads started there, and turn on javac's this-escape lint to catch new ones.

About this answer

Last updated
12 November 2026
Versions it names
Java 21
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "An object is registered as a listener in its own constructor with bus.register(this)....": https://scrivio-interview-library.netlify.app/java/classes-and-objects/b7d6747690/