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 solve the problem of Java instruction rearrangement in multithreaded environment

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

This article introduces the knowledge of "how to solve Java instruction rescheduling in a multithreaded environment". Many people will encounter this dilemma in the operation of actual cases, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

I. Preface

Instruction rearrangement in single-threaded environment helps to improve the execution efficiency of the program, and will not have a negative impact on the program; in multithreaded environment, instruction rearrangement will bring unexpected errors to the program.

II. Problem recovery (1) associated variables

The following is an example that can rearrange 100% recovery instructions.

Public class D {static Integer a; static Boolean flag; public static void writer () {a = 1; flag = true;} public static void reader () {if (flag! = null & & flag) {System.out.println (a); a = 0; flag = false;}} 1, result prediction

The reader method prints the value of variable a to the console only when the flag variable is true.

The writer method first performs the assignment of variable a, and then performs the assignment of variable flag.

If you follow the above analysis logic, then the console print results must be all 1.

2. Instruction rearrangement

If no instruction rearrangement occurs in the code, then when the flag variable is true, the variable a must be 1.

In the above code, there is instruction rearrangement in both the variable an and the variable flag in both method classes.

Public static void writer () {a = 1; flag = true;}

By observing the log output, it is found that there are a large number of zero outputs.

When an instruction rearrangement occurs within the writer method, the flag variable completes the assignment first. If the current thread is interrupted and other threads are calling the reader method, it detects that the flag variable is true, then the value of the variable an is printed. There are more than expected results on the console at this time.

(2) new creates objects

When using the keyword new to create an object, there is instruction rearrangement because of its non-atomic operation, which will have a negative impact on the multithreaded environment.

Public class Singleton {private static UserModel instance; public static UserModel getInstance () {if (instance = = null) {synchronized (Singleton.class) {if (instance = = null) {instance = new UserModel (2, "B");} return instance;}} @ Data@AllArgsConstructorclass UserModel {private Integer userId Private String userName;} 1. Resolution creation process

Create an object using the keyword new, which is roughly divided into the following process:

Create a reference address in the stack space

Using class files as templates to allocate memory in heap space objects

Member variable initialization

Class using the constructor

Assign a reference value to the left storage variable

2. Analysis of reordering process

For the above example, suppose the first thread enters the synchronized code block and starts to create objects. Due to the existence of reordering, the normal process of creating objects is disrupted, which may occur after the stack space creates a reference address, assigns the reference value to the left storage variable, and then interrupts due to the exhaustion of CPU scheduling time slices.

When a subsequent thread detects that the instance variable is not empty, it is used directly. Because the singleton object is not instantiated, direct use will bring unexpected results.

Third, response instruction rearrangement (1) AtomicReference atomic class

Atomic classes are used to encapsulate a group of associated variables into an object, which makes use of the characteristics of atomic operations to effectively avoid the problem of instruction rearrangement.

@ Data@NoArgsConstructor@AllArgsConstructorpublic class ValueModel {private Integer value; private Boolean flag;}

Atomic class should be the first choice to solve the rearrangement of instructions in multi-threaded environment, which is not only easy to understand, but also uses non-heavyweight mutex locks between threads, which is relatively efficient.

Public class E {private static final AtomicReference ar = new AtomicReference (new ValueModel ()); public static void writer () {ar.set (new ValueModel (1, true));} public static void reader () {ValueModel valueModel = ar.get (); if (valueModel.getFlag ()! = null & & valueModel.getFlag ()) {System.out.println (valueModel.getValue ()) Ar.set (new ValueModel (0, false);}

When instruction rearrangement occurs in a group of associated variables, the use of atomic operation classes is a better solution.

(II) volatile keyword public class Singleton {private volatile static UserModel instance; public static UserModel getInstance () {if (instance = = null) {synchronized (Singleton.class) {if (instance = = null) {instance = new UserModel (2, "B");} return instance }} @ Data@AllArgsConstructorclass UserModel {private Integer userId; private String userName;} IV. Understanding of instruction rearrangement 1. Instruction rearrangement exists widely

Instruction rearrangement is not limited to Java programs. In fact, various compilers have instruction rearrangement operations, from software to CPU hardware. Instruction rearrangement is a kind of performance optimization for programs executed by single thread. it needs to be clear that instruction rearrangement in a single-threaded environment will not change the expected results of sequential program execution.

2. Instruction rearrangement in multithreaded environment

Above, two typical multithreading environments are discussed, the negative effects of instruction rearrangement are analyzed, and the coping methods are provided respectively.

For associated variables, they are encapsulated into an object and then manipulated using atomic classes

For new objects, you can modify the target object with the volatile keyword

3. Synchronized locks have nothing to do with reordering

Synchronized locks ensure thread access to specific blocks of code in an orderly manner through mutex locks. The code within the code block is normally reordered according to the policy executed by the compiler.

Although synchronized locks can avoid the adverse effects of reordering in multithreaded environments, the thread overhead caused by mutexes is relatively high and is not recommended.

Instruction rearrangement may still occur for non-atomic operations in synchronized blocks.

This is the end of the content of "how to rearrange Java instructions in a multithreaded environment". Thank you for your reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

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