这个 Java 缓存可以更安全或更快吗?
public class Cache {
private long lastupdateTime = 0L;
private String cachedData = null;
public String getData() {
long now = System.currentTimeMillis();
if (now - lastupdateTime < 30000) {
return cachedData;
}
else {
synchronized (this) {
if (now - lastupdateTime < 30000) {
return cachedData;
}
else {
lastupdateTime = now;
cachedData = getDataFromDatabase();
return cachedData;
}
}
}
}
private String getDataFromDatabase() { ... }
}
最佳答案
是的。即使忽略您没有使 lastupdateTime
或 cachedData
易变的事实,
lastupdateTime = now;
cachedData = getDataFromDatabase();
不正常。
如果 getDataFromDatabase
异常失败,您将已经更新了 lastupdateTime
,因此将继续返回过时数据 30 秒,可能返回 null
如果 getDataFromDatabase
第一次尝试失败。
将 lastUpdateTime
初始化为 Long.MIN_VALUE
不会有任何损失,并且在时钟设置向后的系统上会更可靠地工作。
System.getCurrentTimeMillis
可以去 backwards这不太可能影响 30 秒的缓存,但对于这个用例,确实没有理由不使用 System.nanoTime()
代替。
关于java - 这个 Java 缓存线程安全且最佳吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18498289/