Version 5

    The java.lang.ref package provides limited interaction with the garbage collector.  It contains reference-object classes designed to maintain special references to objects.  Unlike an actual reference type variable, these reference-object classes can refer to objects in a manner where they can still be deleted by the gc.



    One of these classes is java.lang.ref.SoftReference.  The SoftReference class can be used to track when an object no longer has any actual references to it, or hard references.  A soft reference is the second strongest reachability level of an object, next to a hard reference.



    See the javadoc for the java.lang.ref package for more details.





    One funny thing about SoftReference:




    It will go away only when you have almost no Memory, and there are no other references to the referenced object.




    It's very useful to store reflection objects using SoftReferences, however the reference will go away as soon as you are out of memory. So, you have to protected the access of the reference testing for when it's null and probably reconstruct the reflection object. This is because every time you request a reflection on the meatadata you will get a new object (aways).




    I had this problem on JBossSerialization and I created what I called PersistentReference. AOP copied the idea and it's using the same thing to keep reflection (and javassist objects) cached in a safe manner.