声明变量 Final 与延迟实例化
延迟实例化
public class Foo{
private NotSoExpensiveObject o;
public NotSoExpensiveObject getNSEObject(){
if(o == null){
o = new NotSoExpensiveObject();
}
return o;
}
}
声明final
public class Foo{
private final NotSoExpensiveObject o;
public Foo(){
o = new NotSoExpensiveObject();
}
}
声明NotSoExpectiveObject
final 与延迟实例化相比是否有任何优势?或者这纯粹是情境性的?另外,有没有办法延迟实例化并保留 final
修饰符?
谢谢
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();
}
}
Does 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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
延迟实例化可能不是线程安全的,除非您进行同步。
Delayed Instantiation may not be thread safe, unless you synchronize.
您的 Foo 类是否从不同的线程使用?如果是,则需要在延迟初始化解决方案中添加同步。如果您使用“最终”变体,则不必执行此操作。在这种情况下,JVM 保证对 NoSoExpectiveObject 的引用对其他线程可见。
也没有办法保留 Final 修饰符并仍然使用延迟初始化。 Final 成员需要立即初始化或通过构造函数初始化。
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.
Final 只是一个编译时间限制,因此 Finals 成员在声明时或在构造函数中必须内联初始化。当不同的构造函数需要以不同的方式初始化最终成员时,“延迟”最终效果很好。
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.
final
将使它成为常量,不可修改(即CONST
相当于 C,一旦分配它,就无法更改该值)。它与延迟初始化无关可能您看到此代码的地方不希望该值不可修改,因此
final
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 initilizationProbably the place where you seen this code wants not to the value to be non-modifiable and so the
final