Mazyod
Mazyod

Reputation: 22559

When is it a good time to release cached objects in Java?

I am developing a Java desktop application where I have many caches, such as object pools, cached JPanels ...etc.

Example: When a user switches from one Panel to another, I don't destroy the previous one in case the user switches back.

But, The application memory consumption might get high while the system is in desperate need of these memory resources that I am consuming not so justifiably...

In an iOS application, I would release these in "applicationDidReceiveMemoryWarning" method. But in Java... ?

So, When is it a good time to release cached objects in Java?

Upvotes: 4

Views: 242

Answers (1)

mikera
mikera

Reputation: 106371

Caching often isn't a good idea in Java - creating new objects is usually much cheaper than you think, and often results in better performance than keeping objects cached "just in case". Having a lot of long-lived objects around is bad for GC performance and also can put considerable pressure on processor caches.

JPanels for example - are sufficiently lightweight that it's fine to create a completely new one whenever you need it.

If I were you, I'd cache as little as possible, and only do so when you've proved a substantial performance benefit from doing so.

Even if you do need to cache, consider using a cache that uses Soft References - this way the JVM will be able to clear items from the cache automatically if it needs to free up memory. This is simpler and safer than trying to roll your own caching strategy. You could use an existing Soft Reference cache implementation like Guava's CacheBuilder (thanks AlistairIsrael!).

Upvotes: 7

Related Questions