In my program below, I see that the value of the variable scoreis doubled (999000 instead of 499500) is the expected value. A closer look at this suggests that the calculation is performed twice, even if it flaggets true after the first call. Any idea what is going wrong here? The program is single-threaded. The actual calculation involves calling the API to rest, but for the purpose of testing, I deleted it.
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) {
for (int i = 0; i < 1000; i++) {
score = score + i;
flag = true;
}
}
}
}
source
share