【问题标题】:Threadsafe way access class variables线程安全方式访问类变量
【发布时间】:2018-07-30 16:22:24
【问题描述】:

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

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

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

public class TestClass {


    public double testVal;


    public void methodA() {
        testVal = 22.6;
    }



    public double methodB() {
        return testVal;
    }
}

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

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

干杯

【问题讨论】:

  • 我不认为那是线程安全的。您的测试类对象可以由多个线程更新。你想让testVal 变量线程安全吗?
  • 是的,我正在尝试
  • 你为什么不想使用synchronized关键字?
  • 因为我正在移植一个更广泛的应用程序,该应用程序不能允许同步关键字涉及的(小)时间延迟
  • 不存在线程安全问题,因为当前执行的线程只知道自己的实例。

标签: java multithreading thread-safety


【解决方案1】:
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. 

【讨论】:

    猜你喜欢
    • 2019-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多