A memo page that verifies the performance impact when using volatile.
Qualifier to attach to the field. For multithreaded programs, threads can cache field values. If you add volatile, you can exclude it from the cache. (Details on the role of volatile are omitted on this page.)
** Machine spec ** CPU:Intel(R) Core(TM) i5-2400S CPU RAM:8GB OS: windows10 64-bit
** Execution environment ** Eclipse(2020-03 (4.15.0)) Java8
Measure the processing time to count up the int type field 100 million times with volatile added.
private volatile int cnt = 0;
private long exe() {
long start = System.currentTimeMillis();
for (int i = 0; i < 100000000; i++) {
this.cnt++;
}
long end = System.currentTimeMillis();
return end - start;
}
Measured with the above code 10 times and obtained the average value.
result Mean: 964ms
From the above code, change the field to a form that does not use volatile.
private int cnt = 0;
Similarly, the measurement was performed 10 times and the average value was obtained.
result Mean: 7ms
Performance will be worse when volatile is used, but it will not affect in most cases because it takes about the above time to count up 100 million times.
Recommended Posts