开发者

Declaring variable final v. delayed instantiation

开发者 https://www.devze.com 2023-03-05 11:52 出处:网络
Delayed instantiation public class Foo{ private NotSoExpensiveObject o; public NotSoExpensiveObject getNSEObject(){

Delayed instantiation

public class Foo{
    private NotSoExpensiveObject o;

    public NotSoExpensiveObject getNSEObject(){
        if(o == null){
            o = new NotSoExpensiveObject();
        }
        return o;
    }
}

Declaring final

public class Foo{
    private final NotSoExpensiveObject o;

    public Foo(){
        o = new NotSoExpensiveObject();
    }
}

开发者_如何学GoDoes declaring NotSoExpensiveObject final have any advantage over delaying its instantiation? Or is this purely situational? Also, is there a way to delay instantiation, and keep the final modifier?

Thanks


Final is only a compile time restriction and as such finals members must be initialized inline when they are declared or in the constructor. The "delayed" final is nice when different constructors need to initialize the final member differently.


Does declaring NotSoExpensiveObject final have any advantage over delaying its instantiation? Or is this purely situational? Als

final will make it constant , unmodifiable(i.e. CONST equivalent of C, once you assign it you can't change the value ). It has nothing to do with lazy initilization

is there a way to delay instantiation, and keep the final modifier

Probably the place where you seen this code wants not to the value to be non-modifiable and so the final


Delayed Instantiation may not be thread safe, unless you synchronize.


Is your Foo class used from different threads? If yes, you need to add synchronization to the lazy initialization solution. You would not have to do this if you used the 'final' variant. In that case the JVM guarantees that the reference to NoSoExpensiveObject is visible to other threads.

There's also no way to keep the final modifier and still use lazy initialization. Final members need to be initialized immediately or through a constructor.

0

精彩评论

暂无评论...
验证码 换一张
取 消