Code Room
Code reviewHardcr-g235
Subject Thread safetyLevel Senior–Staff~40 minCommon in Concurrency interviewsIndustries Software development

Question

Review this Java holder that publishes an object through a non-volatile field.

Assume `initOnce()` runs exactly once, before readers are told to start. Is unsynchronized publication safe here?

What a strong answer looks like

Separate real bugs from style. Rank issues by severity, point at the root cause rather than the symptom, and suggest a concrete fix — specific and kind.

Talk through your review
Code to reviewjava
class Holder {    private Resource res;                 // not volatile, not final     void initOnce() {                     // called by one init thread        Resource r = new Resource();        r.setup();                        // sets internal fields        this.res = r;                     // (1) publish    }    Resource getResource() {              // called by many reader threads        return res;                       // (2) read without sync    }}
Run or narrate your approach, then ask the coach.