What Is a Soft Reference?

Alex Newth
Alex Newth
Man holding computer
Man holding computer

In the Java® coding language, references constantly are made to objects, strings and variables, even if the programmer is unaware of those references. These references communicate directly with the garbage collector, a function that gathers unneeded information and throws it away so it no longer takes up memory. By default, all references are strong references and are set without any coding, meaning they are not released to the garbage collector. A soft reference allows the data to be thrown away. It is the middle-level reference for all non-strong references.

Whenever a programmer does anything with Java®, be it as simple as making a string or creating complex functions, a reference is made. The programmer does not have to write a reference command; the reference is made automatically and is, by default, a strong reference. This means the data from the reference cannot be thrown away, because they are linked to integral objects needed for the entire script.

Some data need to be thrown away, though, because they otherwise take up a lot of memory. For example, if a programmer builds a script in which serial numbers are used or other temporary pieces of information are gathered or created, holding onto this information becomes detrimental. The Java® program would refuse to throw away the information, even when it is unneeded, and the script would need more and more memory to function.

By specifying a string or section as a soft reference, which needs to be placed in the coding, this tells the garbage collector that the data can be released. Once released, the string or section will read as "null". The garbage collector, depending on its setting, will decide when the data should be thrown out.

There are three non-strong references: soft reference, weak reference and phantom reference. The weak reference is the weakest, and its data is thrown away quickly. Soft references, which are best for scripts where temporary data may be used several times, are next in line. A phantom reference is thrown away almost automatically, within a second, and should be used sparingly.

The length of time a soft reference remains usually depends on the amount of memory in the computer. If the memory is full, then the garbage collector will first destroy all the weak references. When all the weak references are gone, and if the memory still needs to purge data, then soft references will be tossed out next.

You might also Like

Discuss this Article

Post your comments
Forgot password?
    • Man holding computer
      Man holding computer