Method references to same instance+method yield different method reference instances

Nick Williams nicholas+openjdk at nicholaswilliams.net
Mon Jan 20 01:10:30 PST 2014


I'm a little confused by this behavior, so I wanted to verify that this is according to spec and not a bug. Consider the following code:

public class SomeClass
{
    @AfterConstruct
    public void setUp() {
        ...
        registry.addEventListener(this::react);
        ...
    }

    @PreDestroy
    public void tearDown() {
        ...
        registry.removeEventListener(this::react);
        ...
    }
    
    private void react(SomeEvent event) {
        // does something with event
    }
}

I expected this to work, but it does not. The event registry contains a Hashtable of event listeners. The two method references to this::react are identical, so in my mind it would seem that they should pass in the same instance, but they do not. Upon debugging, the method references have different hash codes. This is not only counter-intuitive, but it seems like it's counter-performance, as well. IMO, the method reference this::react should be cached, and all uses of it should use the same instance.

What does the spec say about this?

Nick


More information about the lambda-dev mailing list