java代码味道:我不应该使用volatile字符串吗?

e1xvtsh3  于 2021-06-27  发布在  Java
关注(0)|答案(0)|浏览(846)

我的代码:

private volatile String tokenCache;
    private volatile long tokenLastUpdateTimeStamp;

    private String getToken() throws IOException {
        // cache in 10 minutes.
        if (StringUtils.isNotEmpty(tokenCache) && System.currentTimeMillis() - tokenLastUpdateTimeStamp < 10 * 60 * 1000) {
            return tokenCache;
        }
        tokenCache = xxx;
        tokenLastUpdateTimeStamp = System.currentTimeMillis();
        return tokenCache;

但声纳里有个暗号

Non-primitive fields should not be "volatile"
Marking an array volatile means that the array itself will always be read fresh and never thread cached, but the items in the array will not be. Similarly, marking a mutable object field volatile means the object reference is volatile but the object itself is not, and other threads may not see updates to the object state.

This can be salvaged with arrays by using the relevant AtomicArray class, such as AtomicIntegerArray, instead. For mutable objects, the volatile should be removed, and some other method should be used to ensure thread-safety, such as synchronization, or ThreadLocal storage.

Noncompliant Code Example
private volatile int [] vInts;  // Noncompliant
private volatile MyObj myObj;  // Noncompliant
Compliant Solution
private AtomicIntegerArray vInts;
private MyObj myObj;

我想问:我的用法错了吗?我不认为我的 tokenCache 就像 myObj ;

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题