Video in progress
What is safe publication, and what does letting this escape from a constructor lead to?
Safe publication is a way of handing over an object that guarantees another thread sees it fully constructed. If this is registered as a listener or given to a thread inside the constructor, another thread may see fields that haven't been filled in yet.
📖 Answer
Writing to a plain field is not a safe handoff:
class Holder { Settings settings; } // a plain field
// T1
holder.settings = new Settings(url, timeout);
// T2
Settings s = holder.settings; // s != null, but s.timeout may still be 0
Ways to hand over safely:
- create it in a static initializer;
- write it to a
volatilefield or anAtomicReference; - write it to a field guarded by a lock;
- pass it through a concurrent collection or a
BlockingQueue; - if all of the object's fields are
final, then once the constructor finishes they are seen correctly by any thread.
But that last guarantee works with one condition: this must not escape during the constructor.
class PriceWatcher implements PriceListener {
private final Map<String, BigDecimal> last;
PriceWatcher(PriceFeed feed) {
feed.register(this); // this has "escaped"
this.last = new HashMap<>(); // not written yet
}
public void onPrice(String sku, BigDecimal p) {
last.put(sku, p); // an NPE from another thread
}
}
The feed runs on another thread and may call onPrice right away, when last is still null. The final guarantee is lost too.
The right way is to move registration out of the constructor: a static factory method (create(feed) does new first, then register), or @PostConstruct in Spring. Calling start() on a thread inside a constructor is the same mistake.
Sign up to mark studied questions and save your progress.