3

I am working in a situation where the MethodHandles.Lookup class is utilized often. In this situation, is it a wise idea to keep the value of MethodHandles.lookup() between multiple lookups? (Specifically, the only lookup method I am using is unreflect(java.lang.reflect.Method).)

Would this speed anything up, or would it be irrelevant? Or, would it actually slow it down for some reason?

OllieStanley
  • 712
  • 7
  • 25
  • Consider adding a java-8 tag because it's probably being more closely monitored by the core Java team. You can also do some actual measurements with `jmh`. – Marko Topolnik Sep 18 '14 at 21:04
  • 1
    I suspect you will find they are already cached behind the scenes. In general you should be wary of application-side caches. They're usually more trouble than they're worth, and I speak from bitter experience. – user207421 Sep 19 '14 at 00:10
  • What kind of methods do you unreflect? If they are `public` you can use [`publicLookup()`](http://docs.oracle.com/javase/7/docs/api/java/lang/invoke/MethodHandles.html#publicLookup()) which is already a singleton. – Holger Sep 19 '14 at 08:09
  • @Holger it's an API and the methods are picked out when annotated with a specific annotation - i can't count on them being public – OllieStanley Sep 19 '14 at 15:50
  • But if it’s an API you can’t control whether the Lookup object is cached or not. It’s the owner of these annotated methods who has to get the Lookup object, otherwise it can’t access these non-`public` methods anyway. – Holger Sep 19 '14 at 15:54

1 Answers1

2

As always with performance, the only good answer is test, measure, test again, measure again ...

That being said, yes caching will probably be faster, the question is will it be significantly faster in your context.

The drawback of caching is memory usage and thread safety. MethodHandle itself seems to be immutable (not explicitly documented but looking at the contract, this is most probably the case). MethodHandles.Lookup is used to check for security constraints, so caching might allow you to bypass, or at least change the behaviour regarding security constraints. This might or might not be a concern to you.

Memory usage comes into play if you cache lots of different MethodHandle. You need to make sure your cache is bounded and sized correctly. My guess is that you will not cache a lot of different instances, but that's only a guess...

Guillaume
  • 18,494
  • 8
  • 53
  • 74