Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to understand the multithreading of JAVA

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly introduces "how to understand the multithreading of JAVA". In daily operation, I believe many people have doubts about how to understand the multithreading of JAVA. The editor consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful for you to answer the doubts of "how to understand the multithreading of JAVA"! Next, please follow the editor to study!

Multithreaded computer storage system

To understand the data consistency problem, first look at the computer storage structure, from the local disk to the main memory to the CPU cache, that is, from the hard disk to memory, to the CPU. The general operation of the corresponding program is to check the data from the database to memory and then to CPU for calculation. This description is a little rough. Draw a picture below.

In the industry, this picture is usually painted in the shape of a pyramid. In order to prove that I drew it myself, I drew a rectangle (actually, I can't draw a pyramid).

There is also a cache consistency protocol (MESI) between multiple cores and memory of CPU to ensure internal data consistency. MESI is actually the first letter in the instruction state. M (Modified) modification, E (Exclusive) exclusive, mutually exclusive, S (Shared) sharing, I (Invalid) invalid. Then look at the picture below.

Too detailed state transfer will not be described, so much is mainly to explain why there is a data consistency problem, because there are so many levels of cache, the operation of CPU is not to directly operate the memory but to read the data in memory into the cache first, while the read and write operations in memory will cause inconsistent problems. How to solve the consistency problem? there are two ways of thinking.

Lock the bus, lock the bus during operation, which is very inefficient, so consider the second idea.

Cache consistency, notification per operation (consistency protocol MESI), (but there are still problems in multithreading, which will be discussed later)

JAVA memory model

A little bit about the storage system above is to write the JAVA memory model here.

The Java virtual machine specification attempts to define a Java memory model (java Memory Model) to shield the memory access differences between various hardware and operating systems, so that Java programs can achieve consistent memory access on various platforms.

The memory model is the interaction and rules between memory and threads. Related to compiler, related to concurrency, related to processor.

The main goal of the Java memory model is to define the access rules for each variable in the program, that is, the low-level details such as storing variables in and fetching variables from memory in a virtual machine. The variables here are different from those described in Java programming. They include instance fields, static fields, and elements that make up the array object, but do not include local variables and method parameters, because the latter is thread-private and will not be shared, so there is no competition. In order to achieve better execution performance, the Java memory model does not restrict the execution engine to use processor-specific registers or caches to interact with main memory, nor does it limit optimization measures such as just-in-time compilers to adjust the order of code execution.

The Java memory model specifies that all variables are stored in main memory. Each thread has its own working memory, and a copy of the main memory of the variables used by the thread is kept in the thread's working memory. All operations on variables (reading, assigning, etc.) by the thread must be carried out in the working memory, instead of directly reading and writing variables in the main memory. There is no direct access to variables in each other's working memory between different threads, and the transfer of variable values between threads needs to be completed through the main memory.

The main memory, working memory and Java heap, stack, method area in the Java memory area mentioned here are not the same level of memory partition, and the two are basically unrelated. If the two must correspond reluctantly, then from the definition of variable, main memory and working memory, the main memory corresponds to the object instance data part of the Java heap, while the working memory corresponds to part of the area of the virtual machine stack. At a lower level, the main memory is the memory that corresponds directly to the physical hardware, and in order to get a better running speed, the virtual machine may give priority to storing the working memory in registers and caches, because the main access to read and write is working memory when the program is running.

What I said above is all about memory. In fact, multithreading has something to do with instruction reordering, which can also cause a difference between ending and thinking under multithreaded access. Don't write a long introduction, or it will be too long (JVM has it in the book). The main reason is that the order of execution is optimized when CPU executes instructions. Let's draw a picture and have a look.

The specific theory later, then write some practical information first, directly on the code, a look at it.

Public class HappendBeforeTest {int a = 0; int b = 0; public static void main (String [] args) {HappendBeforeTest test = new HappendBeforeTest (); Thread threada = new Thread () {@ Override public void run () {test.a = 1; System.out.println ("b =" + test.b);}} Thread threadb = new Thread () {@ Override public void run () {test.b = 1; System.out.println ("a =" + test.a);}}; threada.start (); threadb.start ();}}

Guess what might be output? Multiple selection

Avatar 0Borel Borel Bore1 Bore0CWOR Avatar 0BJ0DRAN0DRANING 1BLING 1

The above code is not easy to tune, and then I modified it a little bit.

Public class HappendBeforeTest {static int a = 0; static int b = 0; static int x = 0; static int y = 0; public static void shortWait (long interval) {long start = System.nanoTime (); long end; do {end = System.nanoTime ();} while (start + interval > = end);} public static void main (String [] args) throws InterruptedException {for ( ) {Thread threada = new Thread () {@ Override public void run () {a = 1; x = b;}} Thread threadb = new Thread () {@ Override public void run () {b = 1; y = a;}} Thread starta = new Thread () {@ Override public void run () {/ / because thread threada starts first / / the following sentence makes it wait for thread startb shortWait (100); threada.start ();}} Thread startb = new Thread () {@ Override public void run () {threadb.start ();}}; starta.start (); startb.start (); starta.join (); startb.join (); threada.join () Threadb.join (); a = 0; b = 0; System.out.print ("x =" + x); System.out.print ("y =" + y); if (x = = 0 & & y = 0) {break;} x = 0; y = 0 System.out.println ();}

In this code, the initial values of an and b are 0, and then the two threads start to set axiom1djinxfub and bfu1jinyfuza, respectively. The starta and startb threads in this code are added to allow threada and threadb threads to start as much as possible at the same time, only calling threada and threadb threads respectively. Then the infinite loop initializes all values as long as x and y are not equal to 0 and continues the loop until break when both x and y are zero. Guess if you can break.

As a result, look at the screenshot

Because I didn't record the number of loops, I don't know how many times I looped, and then triggered the conditional break. From a code point of view, B must be set to 1 before outputting An and A must be set to 1 before outputting B. Then why is it that it is zero at the same time? It's very likely that the instructions have been reordered.

Instruction reordering simply means that more than two lines of unrelated code may be executed first instead of the first. That is, the order of execution will be optimized.

How to determine whether the execution order of the code you write will be optimized depends on whether there is a Happens-before relationship between the code. Happens-before means that it can be executed in an orderly manner without any interference. Due to space constraints, Happens-before will not introduce it here.

Here's a brief introduction to volatile, a keyword in java. To put it simply, volatile is to solve the reordering problem. If you write a volatile variable, you must read it later by happen-before. That is, you use the volatile keyword when you write code that you don't want your code to be reordered. Volatile also solves the problem of memory visibility. When executing, there are a total of 8 instructions: lock (lock), read (read), load (load), use (use), assign (assignment), store (storage), write (write), and unlock (unlock).

Volatile mainly deals with four of these instructions. The figure below is as follows

That is to associate load and use with execution, and assign with store with execution. It is well known that there must be load, there must be read, and now load is associated with use, that is, if you want to use in the cache, you must have load, if you want load, you must need read. Generally speaking, to use (use) a variable, you must load (load), and when you load, you must read (read) from the main memory, which solves the visibility of reading. Let's take a look at the write operation, which associates assign with store, that is, store is required after assign. Write (write) after store (storage). That is, when assigning a value to a variable, a series of associated instructions write the value of the variable directly to the main memory. In this way, it is directly accessed from the main memory when it is used, and the memory visibility is achieved from assignment to writing back to the main memory.

Lock-free programming

I read on the Internet that most multithreading writes about locks, AQS and thread pools. Because there are too many online articles, this article does not introduce much. Let's simply write CAS.

CAS is a more magical operation, using it well can make your code more elegant and efficient. It is the core of lock-free programming.

According to CAS, "CAS, or Compare and Swap, is a non-blocking atomicity operation provided by JDK, which ensures comparison-update atomicity through hardware." Is it non-blocking or atomic, which means it's more efficient. Or through the hardware guarantee that this thing is more reliable.

As can be seen from the above figure, when the cas instruction modifies the value of a variable, it is necessary to judge the value first. if the value is equal to the original value, it has not been changed by other threads, it will be modified, and if it has been changed, it will not be modified. The classes under the java.util.concurrent.atomic package in java use the CAS operation. The most common method is compareAndSet. The underlying layer is the compareAndSwap method of the called Unsafe class.

At this point, the study on "how to understand the multithreading of JAVA" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report