在我的下面的程序中,我观察到score变量的值是两倍(999000而不是499500)它的预期值.仔细看看它表明,即使flag在第一次调用后将gets设置为true ,计算也会完成两次.知道这里出了什么问题吗?该程序是单线程的.实际计算涉及调用rest API,但出于测试目的,我已将其删除.
public class DataClient {
public static void main(String[] args) {
System.out.println(CalculationCache.getScore());
}
}
class CalculationCache{
static{
computeScore();
}
private static int score;
public static int getScore() {
computeScore();
return score;
}
private static boolean flag=false;
static void computeScore(){
if(!flag) {
//calculate the score
for (int i = 0; i < 1000; i++) {
score = score + i;
flag = true;
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
问题是由于类初始化的顺序.静态初始化程序按它们定义的顺序执行.变量flag仅在computeScore()被调用后初始化.因此flag将是false当该方法被称为第二时间.您可能想要摆脱静态块
static{
computeScore();
}
Run Code Online (Sandbox Code Playgroud)
如果你想延迟初始化.
| 归档时间: |
|
| 查看次数: |
48 次 |
| 最近记录: |