I was wondering about that since that would make them less useful. If so, is there a way to make memory weakly referenced only \"garbage\" on major GC?
WeakReference
does not prevent collection of object, so if object belongs to young space and reachable only by weak references it will be collected.
SoftReferences
(in HotSpot JVM) act either as weak or strong references dependent on last access timestamps (timestamp of last call to get()
on reference). 'Expiry time' of sotf reference is calculated as free memory size multiplied by coefficient configured via -XX:SoftRefLRUPolicyMSPerMB=T
(e.g. less free memory, short expiry of soft references).
Generally, using JVM references for caching is a bad idea: - it promotes temporary objects to old space, breaking weak generational hypothesis - references are threat in special way by GC increasing minor GC time
If you need cache with eviction strategy it is better to implement it explicitly and account for effecting memory footprint of stored data in eviction policy.