Java 与 Groovy 继承和基于父类的线程上下文

标签 java multithreading exception groovy this

我正在使用 Groovy 2.4.7,并且遇到了意外的行为。让我们看一下这个简单的 Java 代码:

public class InheritanceBugTest {

    private class Parent {

        private volatile String h = "Hello world";
        private volatile String c;

        String getHello() throws InterruptedException {
            Thread t = new Thread(new Runnable() {
                public void run() {
                    c = h;
                }
            });
            t.start();
            t.join();
            return c;
        }
    }

    private class Child extends Parent {

        String getParentHello() throws InterruptedException {
            return getHello();
        }
    }

    public InheritanceBugTest() throws InterruptedException {
        Parent parent = new Parent();
        assert "Hello world".equals(parent.getHello());

        Child child = new Child();
        assert "Hello world".equals(child.getParentHello());
    }

    public static void main(String[] args) throws InterruptedException {

        new InheritanceBugTest();

    }   
}

这显然在 Java 中工作得很好。 现在介绍 Groovy:

class InheritanceBugTest extends Specification {

    private class Parent {

        private volatile String h = "Hello world";
        private volatile String c;

        String getHello() throws InterruptedException {
            Thread t = new Thread(new Runnable() {
                public void run() {
                    c = h;
                }
            });
            t.start();
            t.join();
            return c;
        }
    }

    private class Child extends Parent {

        String getParentHello() throws InterruptedException {
            return getHello();
        }
    }

    def 'test correct Parent behavior'() {

        given:
        def parent = new Parent()
        def hello

        when:
        hello = parent.getHello()

        then:
        hello == 'Hello world'
    }

    def 'test correct Child behavior'() {

        given:
        def child = new Child()
        def hello

        when:
        hello = child.getParentHello()

        then:
        hello == 'Hello world'
    }    
}

在这里,我最终第一个测试运行良好,第二个测试在 Exception in thread "Thread-2" groovy.lang.MissingPropertyException: No such property: h for class: org.codehaus.groovy.InheritanceBugTest 上失败。 .

看来 Groovy 线程在不同的上下文中运行,其中没有 h存在。这种行为正常还是错误?

最佳答案

看起来它已经打开了groovy bug https://issues.apache.org/jira/browse/GROOVY-5438 .

您可以通过将访问修饰符更改为“ protected ”来避免这种情况。

关于Java 与 Groovy 继承和基于父类的线程上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41481884/

相关文章:

java - 无法在 Thymeleaf 模板中设置变量

java - 如何使用 JPA/Hibernate 选择 DDL 主键约束名称

java - 在 Java 对象上同步文件访问

java - 意外的输出...这个输出无论如何都不是我所期望的。这是什么

exception - Fortran 中是否存在异常处理?

java - 如何使用Java测试Selenium2中的下载文件,然后检查下载文件的格式?

java - JOptionPane.showinputdialog 只输入字母或数字以及多项选择

功能与中断调用中的上下文切换?

java - Java 中线程中的线程?

C++ 异常处理指南