This is the second day of my participation in the August Text Challenge.More challenges in August

First the verdict: No.

What is instruction reorder?

Instruction reorder: The compiler and processor can reorder operation instructions.

Note that there is a key premise:

The compiler and processor must comply with the as-if-serial semantics, which means that no matter how much reordering is done (the compiler and processor are trying to improve parallelism), the execution result of a single-threaded program cannot be changed.

What is operation disorder in Java?

Here’s a quote from understanding the Java Virtual Machine in Depth:

If one thread observes another, all operations are disordered, referring to the phenomena of “instruction reorder” and “working memory and main memory synchronization delay”.

What’s the difference in order?

We know that in addition to synchronized, there is also the keyword volatile.

Synchronized guarantees orderliness, visibility, and atomicity, while volatile only guarantees orderliness, visibility, and not atomicity.

Wait, how are they both guaranteed order?

First of all, before we discuss this issue, let’s establish a fact:

Only the volatile keyword in Java disables instruction reordering, at least in JDK1.8.

So where does volatile guarantee order, does synchronized guarantee order?

Actually, orderliness here doesn’t mean the same thing for the two of them.

  • The orderliness of synchronized means that the methods or code blocks modified by synchronized can only be executed by one thread at any time, and the orderliness between blocks or methods is similar to the macroscopic orderliness.

  • Volatile prevents instruction reordering at the bottom through memory barriers, with orders visible between instructions before and after variables, somewhat similar to microscopic orders.

Synchronized relies on the Mutex Lock of the underlying operating system to implement, and monitorenter and Monitorexit instructions can be seen when viewing the corresponding bytecode.

conclusion

In summary, synchronized blocks are ordered from one block to another, but reordering can occur in blocks that are not atomic. Volatile, by definition, prevents reordering, so you need it in double-checked locks.