Home >Java >javaTutorial >The role and usage of volatile keyword in Java parallel programming

The role and usage of volatile keyword in Java parallel programming

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOriginal
2024-04-19 08:24:011156browse

In Java parallel programming, the volatile keyword ensures consistent access to shared variables in a multi-threaded environment: declaring variables volatile to prevent the processor from reordering optimizations. Ensure that all threads access shared variables in a consistent manner to prevent inconsistency. The sample code demonstrates the use of the volatile keyword to correctly calculate counters in a multi-threaded environment.

The role and usage of volatile keyword in Java parallel programming

The role and usage of the volatile keyword in Java parallel programming

Introduction

volatile The keyword is very important in Java parallel programming. It is used to ensure correct access to shared variables in a multi-threaded environment. It does this by preventing the processor from performing reordering optimizations on shared variables.

Function

volatile The keyword has the following functions:

  • Declare one or more variables as volatile sex (or "volatility").
  • Ensure that all threads can access such variables in a consistent manner.
  • Prevent the processor from performing reordering optimizations on it.

Syntax

volatile Keywords can be applied to instance variables and local variables:

//实例变量
private volatile int counter;

//局部变量
public void incrementCounter() {
    volatile int count = counter;
    ...
}

Reordering optimization

In order to improve performance, processors often perform reordering optimization on instructions. However, in a multi-threaded environment, this can lead to inconsistencies in thread access to shared variables.

Consider the following code:

public class Counter {
    private int counter;

    public void incrementCounter() {
        counter++;
    }

    public int getCounter() {
        return counter;
    }
}

If the volatile keyword is not used, the processor may react to the incrementCounter() method and getCounter () The instructions in the method are reordered, resulting in the read counter value being not the latest.

Practical case

The following is an example of using the volatile keyword to ensure that the counter works correctly in a multi-threaded environment:

public class VolatileCounterDemo {

    private volatile int counter;

    public void incrementCounter() {
        counter++;
    }

    public static void main(String[] args) throws InterruptedException {
        VolatileCounterDemo demo = new VolatileCounterDemo();

        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 1000000; i++) {
                demo.incrementCounter();
            }
        });

        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 1000000; i++) {
                demo.incrementCounter();
            }
        });

        t1.start();
        t2.start();

        t1.join();
        t2.join();

        System.out.println("最终计数器值:" + demo.counter);
    }
}

Output:

最终计数器值:2000000

The above is the detailed content of The role and usage of volatile keyword in Java parallel programming. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn