0
class A {
    void b() {}
}

A a = new A();
Runnable c = a::b;

Will c be the same object every time it's initialized?

Didier L
  • 18,905
  • 10
  • 61
  • 103
  • 2
    It's not guaranteed either way. Could be, could not be - up to the JVM. Don't write code that relies on either. In general, don't write code that relies on the notion that these things have a meaningful identity in the first place (don't use them as keys in IdentityHashMaps, don't `synchronized` on them, etc). Trust that the JVM is optimizing for you. Don't 'cache' this in an attempt to make things go faster - it won't work. – rzwitserloot Feb 20 '22 at 21:51
  • @rzwitserloot Yeah, but I suppose I'm ok using `c` in this example as a key in HashSet because it's a regular object at this point and it's not going anywhere until I dereference it. Or am I missing something? – Daniil Lantukhov Feb 20 '22 at 23:05
  • 2
    Yes. __You should not be doing this__ - every doc, spec, and e.g. debate on lambda-dev yells this at you. These aren't meant for that kind of thing. – rzwitserloot Feb 20 '22 at 23:47
  • 2
    Unspecified identity also implies unspecified equality. So this is not a reasonable key for a `HashSet`, even if it is a regular object. As being a regular object is not sufficient for being a valid hash key. – Holger Feb 21 '22 at 09:51

0 Answers0