Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

java reflection - flyweight pattern

 
Anamitra Bhattacharyya
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All
I am a bit surprised to see that in the java reflection package - none of the api utilize this flyweight pattern. If I see the getDeclaredMethod api I would assume that everytime the same Method object should be returned if the signature is same. But surprisingly everytime a different Method instance is returned - though they all point to the same method. Does anyone have any idea why its designed that way - rather why there is no caching of the Method instances?
TIA
Anamitra
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Caching is a gamble that the cost of memory to hold the cache is less than the cost of object creation. (Cost being overall negative impact on how the program runs.) Apparently the designers didn't want to make that bet. If somebody asks for a zillion different methods a cache will chew up memory and deliver no value. If somebody asks for the same method a zillion times, I guess they'll soon figure out they need a cache and write one. Did that make sense?
 
Anamitra Bhattacharyya
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I do get your point - but see the case of String objects - they are pooled by the java runtime itself. So I was not sure whether its just "not my responsibilty" approach or there was some real technical reason behind not implementing the cache in the reflection api - like dydnamic classloading etc.
thanks
Anamitra
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24208
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The JVM pools only some string objects -- those that it itself needs to pool to ensure specific guarantees made by the Java language. It doesn't pool all strings.
A similar argument that comes up from time to time: calculating hashCode() for a String is an expensive operation. Why not cache the result? The answer used to be that, while that would speed up some software, it would penalize everybody by occupying more space per string.
Eventually, somebody changed their mind, because nowadays String does cache the hashCode value.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic