When is the 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 do not destroy the previous one if the user switches back.

But the memory consumption of the application can become high, while the system desperately needs these memory resources, which I consume not so reasonably ...

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

So, when is the right time to release cached objects in Java?

+4
source share
1 answer

Caching is often not a good idea in Java . Creating new objects is usually much cheaper than you think, and often leads to better performance than storing objects cached "just in case". Having a large number of long-lived objects is bad for GC performance, and can also put significant pressure on processor caches.

JPanels, for example, are light enough that it's great to create a whole new one when you need it.

If I were you, I would cache as little as possible, and only so when you have proven the substantial benefits of this.

Even if you need to cache, consider using a cache that uses Soft References - this way the JVM can clear items from the cache automatically if memory needs to be freed. This is easier and safer than trying to flip your own caching strategy. You can use an existing Soft Reference cache implementation such as Guava CacheBuilder (thanks AlistairIsrael!).

+7
source

Source: https://habr.com/ru/post/1397722/


All Articles