NOTE

6.3 3.volatile

These volatile notes examine ordering, visibility, and atomicity, compare volatile with synchronized, and record usage scenarios.

JavaCreated Updated 2 min readhistorical

This is a historical learning note and may contain outdated or incomplete understanding.

1. What Is It?

A lightweight lock in Java. It mainly guarantees ordering, visibility, and a degree of atomicity.

  • Lightweight
    Compared with synchronized, volatile does not cause context switching (it does not block threads).
  • Atomicity
    Reads and writes of a single volatile variable are atomic, but compound operations such as volatileVar++ are not atomic.
  • Visibility
    A volatile write also writes the data to main memory and invalidates other threads’ working-memory copies, so those threads must read the data from main memory.
  • Ordering
    A read of a volatile variable always sees the most recent write to that variable by any thread.

2. When Is volatile More Suitable Than synchronized?

2.1. Example

In the following program, thread1 will not stop.

public class VolatileTest
{
    private static boolean isRunning = true;

    public static void main(String[] args) throws InterruptedException
    {
        Thread thread1 = new Thread(()->{
            System.out.println("thread1 is running");
            while (isRunning)
            {

            }
            System.out.println("thread1 will be stopped");
        });
        thread1.start();

        Thread.sleep(1000);

        Thread thread2 = new Thread(()->{
            System.out.println("thread2 is running");

            isRunning = false;

            System.out.println("thread2 change isRunning flag");
        });
        thread2.start();

        thread1.join();
        thread2.join();
    }
}

2.2. Analysis of Why It Does Not Stop

  1. Thread1 loads isRunning from main memory into working memory. Its value is true, so the thread keeps running.
  2. Thread2 loads isRunning from main memory into working memory, changes it from true to false, writes it back to working memory, and then writes it back to main memory.
  3. Thread1 keeps reading this variable from working memory, where it remains true, so the thread still cannot stop.

2.3. Solution

Declare isRunning as volatile.

public class VolatileTest
{
    private static volatile boolean isRunning = true;

    public static void main(String[] args) throws InterruptedException
    {
        Thread thread1 = new Thread(()->{
            System.out.println("thread1 is running");
            while (isRunning)
            {

            }
            System.out.println("thread1 will be stopped");
        });
        thread1.start();

        Thread.sleep(1000);

        Thread thread2 = new Thread(()->{
            System.out.println("thread2 is running");

            isRunning = false;

            System.out.println("thread2 change isRunning flag");
        });
        thread2.start();

        thread1.join();
        thread2.join();
    }
}

2.4. volatile vs. synchronized

volatile synchronized
Memory-model properties Visibility, ordering Visibility, ordering, atomicity
Causes thread blocking No Yes
Scope Variable level Variable, method, and class levels

3. Assembly-Code Experiment

3.1. Download and Compile hsdis-amd64.dll

Refer to How to build hsdis-amd64.dll and hsdis-i386.dll on Windows or hsdis-amd64.7z.

3.2. Put It in the JRE bin Directory

3.3. Comparison Experiment

  • With volatile
public class TestVolatile
{
    private static volatile int i = 0;
    public static void main(String[] args)
    {
        test();
    }

    private static void test()
    {
        i++;
    }
}
  • Without volatile
public class TestVolatile
{
    private static int i = 0;
    public static void main(String[] args)
    {
        test();
    }

    private static void test()
    {
        i++;
    }
}

3.4. Run with JVM Parameters

-server -Xcomp -XX:+UnlockDiagnosticVMOptions -XX:-Inline -XX:CompileCommand=print,*TestVolatile.test

In IDEA:

3.5. Compare the Output

The results are in the attachments:

A Beyond Compare screenshot is shown below:

4. Analyze the Principle from the Experimental Result

At the assembly level, the volatile version has an additional instruction compared with the ordinary version: lock addl $0x0,(%rsp). This instruction acts as a memory barrier.

  1. Prevent instructions on the two sides of the barrier from being reordered.
  2. Force dirty data in write buffers and caches back to main memory and invalidate the corresponding cached data.

4.1. Visibility

The second effect of the memory barrier provides visibility:

  • a volatile write also writes data to main memory and invalidates other threads’ working-memory copies;
  • other threads must read from main memory when performing a volatile read.

4.2. Ordering

The first effect of the memory barrier provides ordering, as shown below.

A release barrier [LoadStore + StoreStore] is inserted before a volatile write so that all reads and writes before the barrier are committed before that volatile write.

An acquire barrier [LoadLoad + LoadStore] is inserted after a volatile read so that the volatile read is committed before all reads and writes after the barrier.

5. References

Discussion

Sign in with GitHub to comment. Discussions are stored as GitHub Issues.View on GitHub