In Java, a soft reference is a reference to an object that can be deleted if memory is tight. It's implemented by the java.lang.ref.SoftReference class.

Okay, first, a primer.

In object-oriented programming languages (like Java), you do things based on objects (natch). So you have a class Record, and you create a new object R1 of class Record, and then you can do things to R1 like R1.addName() and R1.printData() and so on and so forth. Once you create an object, a reference (in essence a copy) is also created in memory - it's much faster to just copy data in from memory than to regenerate R1 every time.

But what happens when you run out of memory? 

One of the best things about Java programming is it features automatic garbage collection. That is, once an object isn't needed by the program, Java automatically frees up the memory for any future uses. This all but eliminates memory leaks from your programming (there's always an exception!) - which is great! But what's even nicer is that when it kills the object, it doesn't kill the reference - not right away, at least.

One of the subtler aspects of this garbage collection is you can set how "durable" a reference to an object is. Say your program requires you to be able to access random records based on an incoming data stream. You may need to access R1 once in 8 hours, or 8 times in one hour. By creating a soft reference you basically are saying, "hold onto this as long as you can, but if you need the memory, you can kill it."

So as your record references start piling up, eventually you'll run out of allocated memory for the program, and a new record will be required. That's when the soft references start disappearing.

Contrast this with weak reference and phantom reference.

Log in or registerto write something here or to contact authors.