java - "non-concurrent multithreading"是否需要 volatile 关键字?

标签 java multithreading akka volatile

我有一个由多个线程使用的对象,但从不同时使用(始终只有一个线程在其上执行方法)。它包含几个非最终字段。现在我想知道是否必须将所有字段标记为 volatile ,以确保下一个线程(之前可能使用过该对象)将看到更改。如果没有 volatile ,线程在什么时候会从另一个线程获取更改?有任何保证吗?

如果我必须使用 volatile,Akka 如何解决这个问题?

Behind the scenes Akka will run sets of actors on sets of real threads, where typically many actors share one thread, and subsequent invocations of one actor may end up being processed on different threads. Akka ensures that this implementation detail does not affect the single-threadedness of handling the actor’s state.

最佳答案

如果发生之前关系是在对象外部建立的,则不需要需要使成员变量 volatile 。即使没有同步块(synchronized block),也可以建立发生之前关系。以下示例使用 volatile 来实现此目的——保证写入者和读取者不能同时访问同一对象。在这种情况下,可以保证读者读取到正确的值。

class Foobar {
    public static volatile Foobar instance = new Foobar(42);
    public int value;
    public Foobar(int value) { this.value = value; }
}

int reader() {
    return Foobar.instance.value;
}

void writer(int value) {
    Foobar.instance = new Foobar(value);
}

因此,有趣的部分是对象外部的代码 - 确保只有一个线程可以访问该对象。可以编写保证它的代码,而无需建立发生之前关系。但是,这会很奇怪,您应该解决那里的问题,而不是使成员变量 volatile

关于java - "non-concurrent multithreading"是否需要 volatile 关键字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24592757/

相关文章:

scala - 如何使用 react 性流进行NIO二进制处理?

Java : How to implement Multi-Threading into a recursive folder size finder algorithm?

java - 使用 coldfusion 或 java 压缩文件的最有效方法

java - 对具有多个值的数据库查询进行排序

java - 发生异常时记录?

java - 初始化时死锁

python - 多个线程在 Python 中同时写入日志文件

server - 什么网络服务器使用 akka akka-http 以及如何获取它的版本?

java - 使用 Fabric8 关闭 Kubernetes 客户端

java - 如何显示时间戳之间超过 24 小时的时差