I am very curious that whether in Java there is any way to release the memory as needed – just as the UIApplicationDidReceiveMemoryWarningNotification in iOS?
For example, I may have an array used as a caching structure in my program, and when the JVM has memory pressure (heap space is draining), I can get some notification to release some memory by forcing GC and clean the array cache?
Please comment if you think the question is not clear to you~
The GC is run automatically when needed, so you don’t need a notification for this.
For caches where you want to manually remove entries when the memory is low, you can use
SoftReferences. If you hold only a soft reference to a cache entry, the garbage collector will automatically remove entries from the cache if it needs more memory.There are already quite a few existing cache implementations which handle this for you (its not trivial to get it right), for example in the Guava library (cf.
CacheBuilder).