如何在Java并发中发生可见性问题? [英] How do visibility problems occur in Java concurrency?

查看:282
本文介绍了如何在Java并发中发生可见性问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读的书:Java并发实践,以更好地了解java并发的工作原理。在第3章第3.1节:可见性有一个例子,在这本书试图显示如何可见性问题发生。下面是示例代码(本书中的代码3.1):

  
public class NoVisibility {
private静态布尔准备;
private static int number;

private static class ReaderThread extends Thread {
public void run(){
while(!ready)
Thread.yield();
System.out.println(number);
}
}

public static void main(String [] args){
new ReaderThread()。start();
number = 42;
ready = true;
}
}

这本书说NoVisibility可以永远循环,因为ready的值可能永远不会对reader线程可见。怎么可能。我的一般理解是,准备将在某个时刻变成真实。但我不明白为什么这不会发生,循环永远。

解决方案

因为ready不会被标记为volatile,并且该值可能会被缓存在开始while循环,因为它在while循环中没有改变。这是抖动优化代码的方法之一。



因此,线程可能在ready = true之前启动,并读取线程本地和永不读取的ready = false缓存





< com / a / 1919476/12860>来源


I am reading the book: "Java Concurrency in Practice" to better understand how java concurrency works. On chapter 3 section 3.1:Visibility There is and example in which the book tries to show how visibility problems occur. Here is the example code (Listing 3.1 in the book):


public class NoVisibility {
    private static boolean ready;
    private static int number;

    private static class ReaderThread extends Thread {
        public void run() {
            while (!ready)
                Thread.yield();
            System.out.println(number);
        }
    }

    public static void main(String[] args) {
        new ReaderThread().start();
        number = 42;
        ready = true;
    }
}

The book says that the NoVisibility could loop forever because the value of ready might never become visible to the reader thread. How is that possible. My general understanding is that ready will become true at a certain time anyhow. But I can't understand why this might not happen and the loop goes forever. Can someone help me to understand this better.

解决方案

Because ready isn't marked as volatile and the value may be cached at the start of the while loop because it isn't changed within the while loop. It's one of the ways the jitter optimizes the code.

So it's possible that the thread starts before ready = true and reads ready = false caches that thread-locally and never reads it again.

Check out the volatile keyword.

Source

这篇关于如何在Java并发中发生可见性问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆