Java内存可见性volatile

概述

JMM规范指出,每个线程都有本身的工做内存(working memory),当变量的值发生变化时,先更新本身的工做内存,而后再拷贝到主存(main memory),这样其余线程就能读取到更新后的值了。
注意:工做内存和主存是JMM规范里抽象的概念,在JVM的内存模型下,能够将CPU缓存对应做线程工做内存,将JVM堆内存对应主存。
html

写线程更新后的值什么时候拷贝到主存?读线程什么时候从主存中获取变量的最新值?hotspotJVM中引入volatile关键字来解决这些问题,当某个变量被volatile关键字修饰后,多线程对该变量的操做都将直接在主存中进行。在CPU时钟顺序上,某个写操做执行完成后,后续的读操做必定读取的都是最新的值。java

内存可见性带来的问题

以下代码片断,写线程每隔1秒递增共享变量counter,读线程是个死循环,若是读线程始终能读取到counter的最新值,那么最终的输出应该是 12345。程序员

public class App {
    // 共享变量
    static int counter = 0;

    public static void main(String[] args) {
        Thread thread1 = new Thread(() -> {
            int temp = 0;
            while (true) {
                if (temp != counter) {
                    temp = counter;
                    // 打印counter的值,指望打印 12345
                    System.out.print(counter);
                }
            }
        });

        Thread thread2 = new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                counter++;
                // 等待1秒,给读线程足够的时间读取变量counter的最新值
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            // 退出程序
            System.exit(0);
        });

        thread1.start();
        thread2.start();
    }
}

在没有volatile的状况下,实际的输出结构以下:缓存

1

Process finished with exit code 0

经过volatile解决问题

将共享变量用volatile关键字修饰便可,以下:安全

// 共享变量
static volatile int counter = 0;

再次执行程序,输出结果以下:bash

12345

Process finished with exit code 0

综上,volatile关键字使得各个线程对共享变量的操做变得一致。在非volatile字段上作更新操做时,没法保证其修改后的值什么时候从工做内存(CPU缓存)刷新到主存。对于非volatile字段的读操做也是如此,没法保证线程什么时候从主存中读取最新的值。多线程

volatile没法保证线程安全性

以下代码片断,多个线程同时递增一个计数器:oracle

public class App {
    // 共享变量
    static volatile int counter = 0;

    public static void main(String[] args) throws InterruptedException {
        Thread thread1 = new Thread(() -> {
            for (int i = 0; i < 10000; i++) {
                counter++;
            }
        });

        Thread thread2 = new Thread(() -> {
            for (int i = 0; i < 10000; i++) {
                counter++;
            }
        });

        thread1.start();
        thread2.start();
        thread1.join();
        thread2.join();

        System.out.println("总和:" + counter);
    }

输入结果:ide

总和:12374

若是volatile能保证线程安全,那么输出结果应该是20000,但上面的代码输出12374,因此说,volatile不能解决线程安全(thread)的问题。
因此,仍是要经过其余手段来解决多线程安全的问题,好比synchronized。性能

volatile和synchronized的区别

在上述的代码示例中,咱们并无涉及到多线程竞态(race condition)的问题,核心点是“多线程状况下,对共享变量的写入如何被其余线程及时读取到”。
synchronized关键字是Java中最经常使用的锁机制,保证临界区(critical section)中的代码在同一个时间只能有一个线程执行,临界区中使用的变量都将直接从主存中读取,对变量的更新也会直接刷新到主存中。因此利用synchronized也能解决内存可见性问题。
代码以下:

public class App {
    // 共享变量
    static int counter = 0;

    public static void main(String[] args) {
        // 读取变量的线程
        Thread readThread = new Thread(() -> {
            int temp = 0;
            while (true) {
                synchronized (App.class) {
                    if (temp != counter) {
                        temp = counter;
                        // 打印counter的值,指望打印 12345
                        System.out.print(counter);
                    }
                }
            }
        });

        // 修改变量的线程
        Thread writeThread = new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                synchronized (App.class) {
                    counter++;
                }

                // 等待1秒,给读线程足够的时间读取变量counter的最新值
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            System.exit(0);
        });

        readThread.start();
        writeThread.start();
    }
}

运行,输入结果:

12345

Process finished with exit code 0

虽然经过synchronized也能解决内存可见性的问题,可是这个解决方案也带来了其余问题,好比性能会比较差。

总结

多线程能够提高程序的运行速度,充分利用多核CPU的算力,但多线程也是“恶魔”,会给程序员带来不少问题,好比本文中的内存可见性问题。volatile可使变量的更新及时刷新到主存,变量的读取也是直接从主存中获取,保证了数据的内存一致性。可是volatile不是用来解决线程安全问题的,没法替代锁机制。

参考:
[1] Java Memory Model - Visibility problem, fixing with volatile variable
[2] Guide to the Volatile Keyword in Java
[3] Managing volatility
[4] Java Volatile Keyword
[5] Thread and Locks

相关文章
相关标签/搜索