简体   繁体   English

可变实例对象的可见性

[英]Visibility of mutable instance objects

As per the book “Java concurrency in practice”, the below code might execute forever or value of number may still be 0 when ready is true and the recommendation was to define the variables as volatile.根据“Java 并发实践”一书,下面的代码可能会永远执行,或者当 ready 为真时,数字的值可能仍然为 0,建议将变量定义为 volatile。 However the below listed program always seems to return the correct value (42) instead of stale value even after I tried this multiple times.然而,即使在我多次尝试之后,下面列出的程序似乎总是返回正确的值(42)而不是陈旧的值。 Is this a phenomenon that occurs very rarely?这是一种很少发生的现象吗?

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

    private static class ReaderThread extends Thread{
        public void run(){
            System.out.println("Thread started =" + ready + " " + number);
            while(!ready){
                Thread.yield();
            }
            System.out.println("value is" + number);
        }
    }

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

Is this a phenomenon that occurs very rarely这是一种很少发生的现象吗

Yes, rare.是的,很少见。 However, given computers that do things billions of times per second, rare is quite common .然而,鉴于计算机每秒执行数十亿次操作,罕见是很常见的

Whenever accessing resources across threads, you must address thread-safety .每当跨线程访问资源时,您必须解决线程安全问题 Otherwise, your app in deployment will suffer sporadic bugs that are terribly difficult if not impossible to solve.否则,您部署中的应用程序将遭受零星的错误,这些错误即使不是不可能解决也是非常困难的。

By this same logic, testing for concurrency bugs is notoriously difficult, as you have seen in your Question.按照同样的逻辑,正如您在问题中看到的那样,测试并发错误是出了名的困难。

Always look to avoid threaded code where possible.始终尽可能避免使用线程代码。 For example, utilize immutable objects or defensive copies .例如,利用不可变对象防御性副本

Required reading: Java Concurrency in Practice by Brian Goetz, et al.必读阅读:Brian Goetz 等人的Java Concurrency in Practice

Author says server JVM performs more optimisation then the client JVM.作者说服务器 JVM 比客户端 JVM 执行更多优化。 他书中的一段话

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM