Verification of performance impact when using Java volatile

Overview

A memo page that verifies the performance impact when using volatile.

What is 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.)

Performance verification

Environment used for performance verification

** 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

Performance when using volatile

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

Performance without volatile

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

Summary

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

Verification of performance impact when using Java volatile
Handling of time zones using Java
Unexpected exception when using Java DateTimeFormatter
Summary of object-oriented programming using Java
I tried using GoogleHttpClient of Java
Status monitoring of java application using Elasticsearch
Acquisition of input contents using Scanner (Java)
Specify ClassPath when using jupyter + Java with WSL
Try similar search of Image Search using Java SDK [Search]
Example of using addition faster than using StringBuilder (Java)
Story of test automation using Appium [Android / java]
How to get the class name of the argument of LoggerFactory.getLogger when using SLF4J in Java
Verification of [email protected]
[Java] Overview of Java
Don't forget setCalendar or setTimeZone when using Java DateFormat
[Rails] When using ajax, be aware of "CSRF measures".
Things to be aware of when using devise's lockable
[Java] When writing the source ... A memorandum of understanding ①
Performance verification of Red Hat Decision Manager plan optimization
Differences in code when using the length system in Java
[Java] Things to be aware of when outputting FizzBuzz
[Java10] Be careful of using var and generics together