views:

96

answers:

2

Is there a way in Java to do something just before running out of memory. For example, keeping a list of previous document states (for undo) and only removing very old states when memory is about to be exhausted?

+2  A: 

For example, keeping a list of previous document states (for undo) and only removing very old states when memory is about to be exhausted?

You may be able to do something with SoftReference. Note also the general documentation for the java.lang.ref package. If the objects are only reachable via a SoftReference, they'll be garbage collected before an out of memory error occurs. Note however that VMs aren't required to keep those references prior to such an event or make any guarantees about which order they might be cleared in. You might be best combining them with some form of persistence.

McDowell
+1  A: 

Yes, it is certainly possible.

I would probably use a list of SoftReferences for your previous document states. These are guaranteed to be disposed of before an out of memory exception occurs.

At some periodic interval, you can clean null references out of the list.

I would also recommend keeping a normal reference to the most recent state so that you can always guarantee at least one undo :-)

It will depend on the JVM implementation, but if you are lucky the JVM will keep the most recent states and dispose of the oldest ones. This is not strictly required in the JVM spec but is the recommended behaviour.

mikera