I want to cache data produced by my application in memory, but if memory becomes scarce I would like to swap the data to disk.
Ideally I would want to be notified by the VM that it needs memory and write my data to disk and free some memory that way. But I don't see any way to hook myself into the VM in a manner that notifies me before an OutOfMemoryError
occurs somewhere (most likely in code not related to the cache in any way).
The Reference classes in java.lang.ref
do not seem to be of any use in this case, their notification mechanism (ReferenceQueue
) only triggers after the reference has already been reclaimed by the GC. Then it would be too late to save the data to disk.
What alternatives are available to manage the heap memory efficiently? (do not swap to disk until absolutely unavoidable)
Edit1: In response to the comment "The OS already does that for you" - this only covers part of the issue - the amount of memory the OS can allocate is a limited resource. There are also other limits than the amount of memory available to the OS that need to be considered here:
- The limit imposed by the VM's architecture (
32-Bit VM
) - The limit of memory that can be allocated to the VM's process (
32-Bit OS
) - The limit possibly imposed on the VM using the
-Xmx
option
Simply running the VM with unlimited heap size will not prevent it from running out of memory, even if the OS still has plenty available it may not be available to the VM for above reasons.