Quantcast
Channel: Lazy initialization without synchronization or volatile keyword - Stack Overflow
Viewing all articles
Browse latest Browse all 5

Answer by artbristol for Lazy initialization without synchronization or volatile keyword

$
0
0

I think the statement is untrue. Another thread can see a partially initialized object, so the reference can be visible to another thread even though the constructor hasn't finished running. This is covered in Java Concurrency in Practice, section 3.5.1:

public class Holder {    private int n;    public Holder (int n ) { this.n = n; }    public void assertSanity() {        if (n != n)            throw new AssertionError("This statement is false.");    }}

This class isn't thread-safe.

If the visible object is immutable, then I you are OK, because of the semantics of final fields means you won't see them until its constructor has finished running (section 3.5.2).


Viewing all articles
Browse latest Browse all 5

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>