最终字段和线程安全 [英] final fields and thread-safety

查看:109
本文介绍了最终字段和线程安全的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了是线程安全的,或者它是否足够没有修饰符方法,它是否应该是有目的不可变的java类'final'的所有字段,包括超级字段?

Should it be all fields, including super-fields, of a purposively immutable java class 'final' in order to be thread-safe or is it enough to have no modifier methods?

假设我有一个非最终字段的POJO,其中所有字段都是某些不可变类的类型。这个POJO有getter-setters,以及一个构造函数,它设置了一些初始值。如果我使用敲除修饰符方法扩展此POJO,从而使其不可变,扩展类是否是线程安全的?

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 wich sets some initial value. If I extend this POJO with knocking out modifier methods, thus making it immutable, will extension class be thread-safe?

推荐答案

为了在线程安全的方式中使用没有 final 字段的有效不可变对象,在初始化后使对象可用于其他线程时需要使用安全发布惯用法之一,否则这些线程可以看到处于部分初始化状态的对象(来自 Java Concurrency in Practice ):

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):



  • 从静态初始值设定项初始化对象引用;

  • 将对它的引用存储到volatile字段或AtomicReference;

  • 将对它的引用存储到正确构造的对象的最终字段中;或

  • 将对它的引用存储到一个被锁定正确保护的字段中。

  • Initializing an object reference from a static initializer;
  • Storing a reference to it into a volatile field or AtomicReference;
  • Storing a reference to it into a final field of a properly constructed object; or
  • Storing a reference to it into a field that is properly guarded by a lock.

将不可变对象的字段声明为 final 释放此限制(即,它保证如果其他线程看到对该对象的引用,它们也会看到完全初始化状态下的 final 字段。但是,在一般情况下,它不保证其他线程一旦发布就可以看到对象的引用,因此您可能仍需要使用安全发布来确保它。

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 its final 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.

请注意,如果您的对象实现了一个接口,您可以使用 Collections.unmodifiableList()等使用的方法:

Note that if your object implements an interface, you can use an approach used by Collections.unmodifiableList(), etc:

class ImmutableFooWrapper implements IFoo {
    private final IFoo delegate; // final provides safe publication automatically

    public ImmutableFooWrapper(IFoo delegate) {
        this.delegate = delegate;
    }
    ...
}

public IFoo immutableFoo(IFoo foo) {
    return new ImmutableFooWrapper(foo);
}

这篇关于最终字段和线程安全的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆