This is the 21st day of my participation in Gwen Challenge

Change the order of execution

The compiler, JVM, or CPU work together to maximize program efficiency by changing the order of execution. Generally, when coding, the code execution is in a certain order to ensure that we can complete certain logic, but when executing the code in THE JVM, the code execution order will be adjusted according to the needs, that is, to maximize performance. But this adjustment does not affect the results of program execution.

a = 3
b = 2
a = a + 1;
Copy the code

This is the JVM execution of the code above, where we load a, assign to a, and then save it to memory, as in the next two statements.

Load a
Set to 3
Store a

Load b
Set to 2
Store b

Load a
Set to 4
Store a
Copy the code

We found that load A was executed twice during execution and we need to optimize this. The specific optimization is as follows

a = 3
a = a + 1

b = 2
Copy the code
Load a
Set to 3
set to 4
Store a

Load b
Set to 2
Store b


Copy the code

These specific optimizations are done in the JVM.

The representation of consistency in multithreading, also known as concurrency

So if we look at the top core, we have four cpus, and each of them has a registers, and then L1 cache, which is not that big because the CPU reads memory directly from there so it’s really fast. And then L2 level 2 cache where the two cores are shared. By the time you get to 3L the cache is the area of memory shared by all the cores. The farther away the cache is from the CPU, the faster the cache is accessed and the larger its capacity is.

public class FieldVisibility{ int x = 0; public void writerThread(){ x = 1 } public void readerThread(){ int r2 = x; }}Copy the code

Create a FieldVisibility class, initialize x = 0, and provide two methods to read and write x on different threads.

Then create two instances of FieldVisibility that call the read and write methods to read and write X.

When an instance calls the writerThread method to change the value of x to 1, x = 1 is stored only in the local cache and not updated to the shared cache. So when another instance calls readerThread to get the value of x, it still gets 0 instead of 1.

This is the field visibility problem.

public class FieldVisibility{ volatile int x = 0; public void writerThread(){ x = 1 } public void readerThread(){ int r2 = x; }}Copy the code

When we modify field x with the keyword volatile, the shared cache is updated when x changes, ensuring that the change in x is visible to other methods.