Aside from the potentially problematic memory leak inherent to caching objects in this manner.
Are you absolutely sure that working without a caching mechanism will devestate your application's performance, and it's not merely an attempt at premature optimization? Still, if a cache is warranted, this implementation might give you headaches further down the line, because it will never allow any of the cached objects to become eligible for garbage collection. Note that this depends entirely on the situation and it might never pose a problem in your specific situation, but it's definitely something to be wary of.
Build a man a fire, and he'll be warm for a day. Set a man on fire, and he'll be warm for the rest of his life.
posted 9 years ago
Adam Smolnik wrote:An unintended side effect is possible according to me - (redundant) creation of several new FooClass(barCode) instances during simultaneous initial access.
Yes. But those objects (the redundant copies) will be available for GC just after the method returns. I did not find a solution for that, any ideas?
Jelle Klap wrote:
Aside from the potentially (...)
Thanks for the info. Do you have any ideas how to solve my problem if I am determined to use a cache? I will access this method very frequently, and the pool of the objects can be 8-15 maximum.
Is there a way to implement such valueOf methods? I looked at the JDK sources and those are different case, since I have no idea what barCode can be.
I am sure that I will have a maximum of about 15 objects I this cache. But the method will be called veery frequently. So I want to use it to optimalise memory usage so that I dont create lots of equal immutable objects.