Newerth
Newerth

Reputation: 574

Java vs Groovy inheritance and parent class based thread's context

I am using Groovy 2.4.7 and I came across an unexpected behavior. Let's have this simple Java code:

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();

    }   
}

This obviously works fine in Java. Now for 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'
    }    
}

Here I end up with the first test running fine and the second test failing on Exception in thread "Thread-2" groovy.lang.MissingPropertyException: No such property: h for class: org.codehaus.groovy.InheritanceBugTest.

So it seems the Groovy thread runs in a different context where no h exists. Is this behavior ok or is it a bug?

Upvotes: 0

Views: 253

Answers (1)

WyMuT_CoCHa
WyMuT_CoCHa

Reputation: 321

Looks like it's opened groovy bug https://issues.apache.org/jira/browse/GROOVY-5438.

You can avoid it by changing access modifier to 'protected'.

Upvotes: 1

Related Questions