Home > Java > javaTutorial > body text

The role and usage of volatile keyword in Java parallel programming

WBOY
Release: 2024-04-19 08:24:01
Original
1065 people have browsed it

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;
    ...
}
Copy after login

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;
    }
}
Copy after login

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);
    }
}
Copy after login

Output:

最终计数器值:2000000
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!