首页 > 解决方案 > 线程安全方式访问类变量

问题描述

我在其他地方找不到我的问题的任何明确答案,所以我决定问。

我正在将代码移植到 Java 中并使其成为线程安全的。我在对象上应用尽可能多的 getter/setter 并传递它们。显然这些值没有设置为静态的。但我也在寻找其他角度。

对于任何特定线程,我希望类中的所有方法都能够在没有其他线程干扰的情况下访问类变量(并且没有同步变量关键字),以下是否可以接受?

public class TestClass {


    public double testVal;


    public void methodA() {
        testVal = 22.6;
    }



    public double methodB() {
        return testVal;
    }
}

如果我创建 in 的实例TestClass并在该对象上main调用methodAthen ,它将返回我的. 这个问题将通过类中不同方法共享的许多值进行扩展,因为我只是展示了一个简单的演示。methodBtestVal

这是一个好的线程安全方法吗?如果我是正确的,这些数据将存储在线程堆栈而不是堆中?

干杯

标签: javamultithreadingthread-safety

解决方案


There are many ways to make your class thread safe.

1. You can make your variable as volatile as in the example you have asked , if the current state of testval does not depend upon the previous state
2. You make the variable as private and volatile and use synchronization for all the methods that are modifying the state of your object.
3. Make the class as immutable
4. Make the calss as stateless
5. Guard all the method with synchronized keyword that are modifying the state of the variables. 

推荐阅读