简体   繁体   English

通过访问器检索的实例成员的线程安全

[英]Thread safety of an instance member retrieved through accessors

Class A 's methods are accessed by two threads. A的方法是通过两个线程访问。 One thread updates it. 一个线程更新它。 The other retrieves its member. 另一个检索其成员。

public class A {
    private V v;

    public V getV() {
        return v;
    }

    public V updateV(A a, B b, Cc) {
        //complex logic updating V
    }
}

How can I make V thread safe? 如何使V线程安全?

The easiest way to make V thread safe is to make it immutable (by making final all its non static fields) then in A you simply affect a new instance of V in updateV as next: 使V线程安全的最简单方法是使其不可变 (通过使其所有非静态字段最终化),然后在A您只需在updateV影响V的新实例,如下所示:

public class A {
    private V v;

    public synchronized V getV() {
        return v;
    }

    public synchronized V updateV(A a, B b, Cc) {
        //complex logic updating V
        this.v = new V(...);
        return v;
    }
}

As you can see to make A thread safe I simply added the keyword synchronized to the getter and the setter to prevent concurrent read and write but if it is not needed in your case you can sill make v volatile as next: 如您所见,为了使A线程安全,我只是将关键字sync synchronized到getter和setter上,以防止并发读写,但是如果您不需要这样做,则可以使v volatile如下:

public class A {
    private volatile V v;

    public V getV() {
        return v;
    }

    public V updateV(A a, B b, Cc) {
        //complex logic updating V
        this.v = new V(...);
        return v;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM