This is the 24th day of my participation in Gwen Challenge.

Many people are irritated by the Volatile keyword, a humble Java keyword that confuses too many heroes. At first look at it, feel very simple, look at it carefully, only to find disturb. This article takes you from deep to shallow analysis of this keyword.

One, soul torture

Were you asked the following questions that year, somewhere you wanted to fight?

  • volatileWhat is it related tosynchronizedThe difference between? Where have you seen it used?
  • Which scenarios are suitable for useVolatile?
  • volatileWhat problem is it to solve? What are its advantages and disadvantages?
  • Talk aboutvolatileUnderlying principles? Say againMESI?
  • Do you knowhappen-beforeThe principle?

COMBO, you can’t handle it. Who am I? Why am I here? It’s getting late. Maybe I should get some rest.

Ii. Case analysis

Let’s walk through this keyword with an example.

/** * thread safely */ //public static volatile boolean run = true; /** * thread not safely */ public static boolean run = true; public static void main(String[] args) throws InterruptedException { new Thread(()->{ int i=0; while (run){ i++; Thread.yield(); System.out.println(i+" loading..." ); } }).start(); System.out.println("Main Thread ready to sleep..." ); TimeUnit.SECONDS.sleep(10); System.out.println("Main Thread finish sleep..." ); run= false; }Copy the code

The above example demonstrates the difference between using the Volatile keyword and not using it.

Public static Boolean run = true;Copy the code

Using thread-unsafe notation, it turns out that there is a fairly small probability that the child thread will stay in the RUNNABLE state and stop forever. Notice that the probability is very small, I run it tens of thousands of times before I get one child thread that doesn’t stop. But this one could lead to a serious production accident.

Public static volatile Boolean run = true;Copy the code

The code above is thread-safe and fundamentally solves the problem of endless loops. So why?

For a quick explanation, the core problem is that even though the main thread changes the value, the child thread does not perceive that the main thread changes the run variable to false. Why, I will analyze it in detail later.

Third, what is volatile

The volatile keyword is used when multiple threads modify the value of the same variable. It allows threads to safely access and manipulate the shared variable. This means that multiple threads can use a method and instance at the same time without any problems. This keyword can modify both Java base types and reference types.

While the above description is all about the phenomenon, the underlying principle is that, based on the JMM(Java Memory Model), the volatile keyword is used to mark Java variables as “stored in main Memory.” More precisely, each read of a volatile variable is read from the computer’s main memory, not the CPU cache, and each write to a volatile variable is written to main memory, not just the CPU cache.

As we all know, when multiple threads want to access a shared variable at the same time, there are three aspects to consider, including atomicity, visibility, and orderliness. Atomicity means that there should be no thread interference when another thread performs some operation on the shared data. Visibility means that the effect of a thread’s behavior on the shared data should be felt by other threads; Sequentiality means that instructions should be executed in the same order as expressed in the source code.

Analyze volatile, which has:

  • Visibility. A read to a volatile variable always sees the last write to that volatile variable (by any thread).
  • Atomicity, atomicity to read/write to any single volatile variable. But fori++This compound operation is not atomic.
  • The order,volatileKeyword disables instruction reordering, sovolatileOrder can be guaranteed to a certain extent.

Hello, what about the keyword volatile? (2)


Brother boy, don’t panic to go! Leave a thumbs-up and comment on the discussion. Welcome to the column face interview don’t panic | Java concurrent programming, a raise don’t have to worry about the interview. Also welcome to pay attention to me, must be a longer better man.