Java memory model JMM and volatile keyword

tags: java  jvm  volatile

This article refers to the video, learning summary

Multi-core compact cache architecture

JMM memory model

The Java thread memory model is similar to the CPU cache model. It is based on the CPU cache model. The Java thread memory model is standardized, and the difference between the bottom layer different computers is blocked.

JMM data atomic operation

  • READ: read data from the main memory
  • LOAD: Write the data read by the main memory to work memory
  • Use: Calculate from work memory read data
  • Assign (copy): Re-copy the calculated value to work memory
  • Store: Write the work memory data into the main memory
  • Write: Copy the Store past variable to the variable in the main memory
  • LOCK: Phase the main memory variable, the logo bit thread exclusive state (lock is Store and Write action)
  • UNLOCK: Unlock the main memory variable, and other threads can lock the variable after unlocking

JMM cache inconsistency solution

  • Bus locking (too low)

    The CPU reads the data from the main memory to the cache, which is locked on this data on the bus, so that other CPUs can't read or write this data until this CPU is used to use the data release lock. Other CPUs can read the data.

  • Mesi Cache Consolidation Agreement

    Multiple CPUs read the same data from the main memory to the respective tell cache, when a CPU modifies the data in the cache, the data will immediately go back to the main memory, and other CPUs can be perceived by bus sniffing mechanisms Changes to invalid the data in your own cache

VOLATILE visibility underlying realization principle

JMM memory interaction: volatile modified variable read, load, use operation, and Assign, Store, Write must be continuous, you must simultaneously synchronize the main memory immediately after the modification, must be refreshed from the primary memory, thereby ensuring the Volatile variable Visibility.

The underlying implementation is mainly by assembling the Lock prefix command, which locks the cache of this area (cache line lock) and back to the main memory.

The IA-32 Architecture Software Development Manual Interpretation of the Lock Directive:

  • Write the data of the current processor cache row immediately write back system memory
  • This will write memory operations will cause data invalid (Mesi) protocols for the memory address in other CPUs.

Volatile visibility, atomic, orderless

  • Thread visibility test
public class VolatileVisibilityTest {

    private static boolean initFlag = true;// Do not use volatile modification
    // private static boolean initflag = true; // Use Volatile modified

    public static void main(String[] args) throws InterruptedException {
        new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("waiting data...");
                while (!initFlag) {

                }
                System.out.println("================success=========");
            }
        }).start();

        Thread.sleep(2000);

        new Thread(new Runnable() {
            @Override
            public void run() {
                prepareData();
            }
        }).start();
    }

    public static void prepareData() {
        System.out.println("prepareing data...");
        initFlag = true;

    }

}
  • Atomic test (not guaranteed atomic)
public class VolatileAtomicTest {

    private static int counter = 0;// Do not use volatile modification
    // private static volatile int counter = 0; // Use volatile modification

    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            Thread thread = new Thread(() ->{
                for (int j = 0; j < 1000; j++) {
                    counter++;
                }
            });
            thread.start();
        }
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(counter);
    }

}
  • Ordered test
public class VolatileReOrderSample {

    private static int x = 0, y = 0;// Do not use volatile modification
    private static int a = 0, b = 0;// Do not use volatile modification
    
    // private static volatile int x = 0, y = 0; // Use Volatile modified
    // private static volatile int a = 0, b = 0; // Use volatile modification

    public static void main(String[] args) throws InterruptedException {
        int i = 0;
        for (; ; ) {
            i++;
            x = 0;
            y = 0;
            a = 0;
            b = 0;

            Thread t1 = new Thread(new Runnable() {
                @Override
                public void run() {
                    shortWait(10000);
                    a = 1;
                    x = b;
                }
            });

            Thread t2 = new Thread(new Runnable() {
                @Override
                public void run() {
                    b = 1;
                    y = a;
                }
            });

            t1.start();
            t2.start();
            t1.join();
            t2.join();

            String result = " + i + "Times (" + x + "," + y + ")";
            if (x == 0 && y == 0) {
                System.out.println(result);
                break;
            } else {
                System.out.println(result);
            }
        }
    }

    /**
           * Wait for a while, time unit nanosecond
     * @param interval
     */
    public static void shortWait(long interval) {
        long start = System.nanoTime();
        long end;
        do {
            end = System.nanoTime();
            Random r = new Random(1);
        } while (start + interval >= end);
    }

}

Explanation: There are two threads here, we constantly cycle, each round of cycle x y a b will be reset to 0, then each value will be modified in two threads. Suppose it will not be reordered, the program is written in order from top to bottom code, then the result value may occur in theory:

  • Thread 1 start execution first, thread 2 after: a = 1, x = B = 0, b = 1, y = a = 1 (Abxy = 1, 1, 0, 1)
  • Thread 2 start execution first, thread 1 after: b = 1, y = a = 0, A = 1, x = b = 1 (Abxy = 1, 1, 1, 0)
  • Thread 1 or 2 is started first, two are not performed; for example, thread 1 is blocked after being executed, thread 2 is immediately executed, execute it to b = 1 block, and then any one start execution of the last result may appear X = 1 and y = 1; then the result may occur in ABXY = 1111;

So theoretical code is in order from top to bottom.x == 0 && y == 0 The situation will not appear;

So do you really don't appear? You can do not use the volatile modification.

The result is that the program will stop execution

In order to perform efficiency, the CPU will reproduce the command; it is possible to appear: thread 1 x = b; take a = 1; front, thread 2 Y = a; shoot B = 1; front, this situation There may be x = 0, y = 0

			// If you reordforward, this may have this situation 
			Thread t1 = new Thread(new Runnable() {
                @Override
                public void run() {
                    shortWait(10000);
                    x = b;
                    a = 1;
                }
            });

            Thread t2 = new Thread(new Runnable() {
                @Override
                public void run() {
                    y = a;
                    b = 1;
                }
            });

So in this case, after modifying Abxy with volatile, if the program does not stop, running unordered, it will not be reordered. The final result will not stop,The conclusion is that Volatile prevents the reordering.

Intelligent Recommendation

Concurrency (1): JMM memory model and volatile keyword

JMM memory model Each Java thread has a self-emptive memory. Operating data, read from the main memory, get a copy, write back to the main memory after the operation is completed. JMM may bring custod...

Volatile and JMM memory model

Volatile is a lightweight synchronization mechanism: Ensure visibility No guarantee of atomicity Prohibit order rearrangement JMM (Java Memory Model) Java memory model Three characteristics: Visibilit...

JMM memory model and volatile

JMM memory model The JMM memory model is the java memory model, also called the java thread memory model. First understand the concept of concurrency and parallelism. ​ Concurrency: It is a logical ar...

Java JMM and the volatile keyword

JMM JMM means JavaMemory model, Not JavaMemory layout, Not the so-called stack, heap, method area. Each Java thread has its ownWorking memory. Operation data, first read from the main memory, get a co...

Java memory model Jmm and volatile visibility

1.volatile Can guarantee the threadVisibility, When a thread is modifying our main memoryShared variableData can be seen by another thread. Note: The volatile keyword cannot guarantee atomicity. Featu...

More Recommendation

Java Memory Model (JMM) and volatile keywords

Java memory model structure diagram The Java thread memory model is similar to the CPU cache model and is based on the CPU cache model. The Java thread memory model is standardized to shield the diffe...

Deep understanding of Java memory model JMM and volatile

The Java Memory Model (JMM) is an abstract concept and does not really exist. It describes a set of specifications or rules through which various variables in the program (including instance fields an...

Java memory model (JMM) and volatile study notes

"In-depth understanding of JAVA virtual machine" The Java Memory Model (JMM) shields the memory access differences of various hardware and OS, and achieves consistency of access results on v...

Understand the JMM memory model and in-depth Volatile keyword principle

One, JMM memory model First look at the CPU multi-core concurrent cache architecture. Because the gap between CPU and memory data read and write is too large, a cache is added to alleviate this gap. T...

JUC concurrent programming VOLATILE keyword detailed explanation with JMM memory model

Volatile Volatile is a lightweight synchronization mechanism provided by JVM Volatile is a Java keyword for modifying variables Volatile only guarantees two points of JMM three major characteristics G...

Copyright  DMCA © 2018-2026 - All Rights Reserved - www.programmersought.com  User Notice

Top