我正在开发一个 Java 桌面应用程序,其中有很多缓存,例如对象池、缓存的 JPanel 等。
例子:
当用户从一个面板切换到另一个面板时,我不会销毁前一个面板,以防用户切换回来。
但是,当系统迫切需要这些内存资源时,应用程序内存消耗可能会很高,而我消耗的内存资源不是那么合理......
在iOS应用程序中,我会在“applicationDidReceiveMemoryWarning”中释放这些资源方法。但在 Java 中...?
那么,什么时候释放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?
在 Java 中,缓存通常不是一个好主意 - 创建新对象通常比您想象的要便宜得多,并且通常会比“以防万一”保留对象缓存带来更好的性能。周围有大量长期存在的对象不利于 GC 性能,并且还会给处理器缓存带来相当大的压力。
例如,JPanel 足够轻量级,因此您可以在需要时创建一个全新的面板。
如果我是您,我会尽可能少地缓存,并且仅当您证明这样做可以带来显着的性能优势时才这样做。
即使您确实需要缓存,也请考虑使用使用 软引用 的缓存 - 这样 JVM如果需要释放内存,将能够自动从缓存中清除项目。这比尝试实施自己的缓存策略更简单、更安全。您可以使用现有的软引用缓存实现,例如 Guava 的 CacheBuilder(感谢 AlistairIsrael!)。
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!).