最终字段和线程安全
为了线程安全,它应该是特意不可变的 java 类“final”的所有字段(包括超级字段),还是没有修饰符方法就足够了?
假设我有一个带有非最终字段的 POJO,其中所有字段都是某个不可变类的类型。这个 POJO 有 getters-setters,以及一个设置一些初始值的构造函数。如果我通过删除修饰符方法来扩展此 POJO,从而使其不可变,那么扩展类是否是线程安全的?
Should it be all fields, including super-fields, of a purposely immutable java class 'final' in order to be thread-safe or is it enough to have no modifier methods?
Suppose I have a POJO with non-final fields where all fields are type of some immutable class. This POJO has getters-setters, and a constructor which sets some initial value. If I extend this POJO with knocking out modifier methods, thus making it immutable, will extension class be thread-safe?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
为了以线程安全的方式使用没有
final
字段的有效不可变对象,您需要在初始化后使对象可供其他线程使用时使用安全发布习惯用法之一,否则这些线程可以看到该对象处于部分初始化状态(来自 Java 并发实践):将不可变对象的字段声明为
final
可以释放此限制(即,它保证如果其他线程看到对该对象的引用,它们也会看到其处于完全初始化状态的final
字段)。但是,一般情况下,它不能保证其他线程在发布该对象后立即可以看到对该对象的引用,因此您可能仍然需要使用安全发布来确保它。请注意,如果您的对象实现了接口,则可以使用 Collections.unmodifyingList() 等使用的方法:
In order to use an effectively immutable object without
final
fields in a thread safe manner you need to use one of safe publication idioms when making the object available to other threads after initialization, otherwise these threads can see the object in partially initialized state (from Java Concurrency in Practice):Declaring fields of your immutable object as
final
releases this restriction (i.e. it guarantees that if other threads see a reference to the object, they also see itsfinal
fields in fully initialized state). However, in general case it doesn't guarantee that other threads can see a reference to the object as soon as it was published, so you may still need to use safe publication to ensure it.Note that if your object implements an interface, you can use an approach used by
Collections.unmodifiableList()
, etc:是的,它是不可变的,因此是线程安全的,但前提是字段是私有的。
Yes, it will be immutable and consequently thread-safe but only as long as the fields are private.