Immutability and reordering

后端 未结 10 681
星月不相逢
星月不相逢 2020-12-04 10:07

The code below (Java Concurrency in Practice listing 16.3) is not thread safe for obvious reasons:

public class UnsafeLazyInitialization {
    private static         


        
10条回答
  •  被撕碎了的回忆
    2020-12-04 10:50

    It is indeed safe is UnsafeLazyInitialization.resource is immutable, i.e. the field is declared as final:

    private static final Resource resource = new Resource();
    

    It might also be considered as thread-safe if the Resource class itself is immutable and does not matter which instance you are using. In that case two calls could return different instances of Resource without issue apart from an increased memory consumption depending on the number of threads calling getInstance() at the same time).

    It seems far-fetched though and I believe there is a typo, real sentence should be

    UnsafeLazyInitialization is actually safe if *r*esource is immutable.

提交回复
热议问题