Cook Computing

Soft References

February 14, 2006 Written by Charles Cook

The second Jeroen Frijters post that caught my attention this week mentioned soft references in Java. I posted about .NET weak references a long time ago but I'd not read about soft references which Java, and not .NET, has. The concept is similar except that whereas objects referred to by weak references can be reclaimed at the next garbage collection, those referred to by soft references survive garbage collections and are only reclaimed if memory is low. The Java 2 spec does not define exactly when objects with soft references will be reclaimed:

... no constraints are placed upon the time at which a soft reference will be cleared or the order in which a set of such references to different objects will be cleared. Virtual machine implementations are, however, encouraged to bias against clearing recently created or recently used soft references.

However the garbage collector is required to clear all soft references before it can throw an OutOfMemory exception.

Jeroen describes how IKVM.NET supports soft references:

Since .NET has no soft references and there is no way to determine if the managed heap is running low, I used a hack to always promote objects referenced by a soft reference to generation 2 and from there on treat them as weak references, which effectively means they will be collected the next time a full GC is run and there are no more strong references to the object.