如果对其他线程缓存的更新没有时间限制,我是否需要使用 volatile

do I need to use volatile if update to other thread'cache is not time-constraint

我有一个使用一种方法的单例对象:

class static single
{
  String static somefileContent;
   public static void set(String str){somefileContent=str;}
   public static String get(){return somefileContent;}
}

我有两个线程,

一个线程在操作中查询single.get()的内容,大约100 times/sec.

另外一个线程监听某个文件,定时用set()方法更新字符串,如果文件被修改,刷新内容。

少数操作使用旧字符串值是可以接受的。

我的问题是:我是否需要 volatile ,因为它没有时间限制?

如果发生最坏的情况,读线程是否永远得不到更新?

我只是想知道使用纯 Java 会发生什么?是的,读取线程可能会在值更新后读取旧值。但正如我所说,多次读取旧值是可以接受的。我想知道旧值是否会永远保留在 CPU 缓存中。

感谢 Vaspar 的回答。

最好使用 ReentrantReadWriteLock 并且不需要使用 volatile 变量。 get 调用应该是共享的 ReadLocked,而 set 调用应该是独占的 WriteLocked。一旦所有线程都获得各自的 ReadLocks,更改就会在所有线程中更新。

All ReadWriteLock implementations must guarantee that the memory synchronization effects of writeLock operations (as specified in the Lock interface) also hold with respect to the associated readLock. That is, a thread successfully acquiring the read lock will see all updates made upon previous release of the write lock.

示例代码:

import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock.ReadLock;
import java.util.concurrent.locks.ReentrantReadWriteLock.WriteLock;


public class Single {
    private static String                       somefileContent = null;
    private static final ReentrantReadWriteLock readWriteLock   = new ReentrantReadWriteLock();
    private static final ReadLock               readLock        = readWriteLock.readLock();
    private static final WriteLock              writeLock       = readWriteLock.writeLock();

    public static String get() {
        try {
            readLock.lock();
            return somefileContent;
        } finally {
            readLock.unlock();
        }
    }

    public static void set(String str) {
        try {
            writeLock.lock();
            somefileContent = str;
        } finally {
            writeLock.unlock();
        }
    }
}