java - 对非 volatile 字段的同步访问线程安全吗?

标签 java thread-safety volatile

我无法在任何地方找到这个特定场景的答案。

如果我从两个线程同时调用 init(),是否保证其中一个调用会看到 time 不再为空? time 是否也需要 volatile

它是不是像join()一样是一个同步点?

private Long time;

synchronized void init() {
    if (time != null) {
        throw new IllegalStateException("Already initialised.");
    }

    this.time = System.currentTimeMillis();
}

最佳答案

当一个线程进入这个synchronized 方法时,它获得一个implicit 锁在实例上,它对实例的state 执行的更改实例对其他线程可见,等待进入同步方法。

when a synchronized method exits, it automatically establishes a happens-before relationship with any subsequent invocation of a synchronized method for the same object. This guarantees that changes to the state of the object are visible to all threads.

文档中的最后一行清楚地提到了它。状态是 volatile 还是 non-volatile 并不重要。

关于java - 对非 volatile 字段的同步访问线程安全吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26210498/

相关文章:

java - 如何访问同一包但不同 jar 中父类的包本地字段?

JavaFX TextField 抛出 NullPointerException

java - 以线程安全的方式填充映射并将该映射从后台线程传递给另一个方法?

java - 我应该同步静态易失变量吗?

c# - 在线程应用程序中使用 C# Volatile 关键字

java - 并发、对象可见性

java - 将指定区域的长纪元时间转换为 UTC 长纪元时间

java - Netbeans:是否可以自定义自动完成?

asp.net - ASP.net HttpRequest 上的静态 HttpClient 线程安全

java - 使用 volatile 更新和交换 HashMap