Sobes.tech
Middle

В чем различия между SoftReference и WeakReference в Java?

sobes.tech AI

Answer from AI

The main differences between SoftReference and WeakReference in Java are related to how the garbage collector affects the objects referenced by these types of references.

Characteristic SoftReference WeakReference
Object retention The object is retained as long as there is enough memory. If memory is critically low, the object may be collected. The object can be collected at any time during the next garbage collection, even if there is enough memory.
Guarantee of object availability More likely that the object will be available until a severe memory shortage occurs. Less likely that the object will be available after garbage collection.
Typical use Caching, where objects should be kept as long as there is enough memory. Implementation of weak associations, where the presence of the object is not critical. For example, in WeakHashMap.
Behavior during memory shortage The object will be collected only in case of severe memory shortage. The collection of the object does not depend directly on memory shortage; it occurs within the normal garbage collection cycle.

Both SoftReference and WeakReference allow access to the referenced object (get() method) and can be enqueued in a ReferenceQueue upon garbage collection.

Example of using SoftReference:

// Object being referenced
Object heavyObject = new Object();

// Creating a SoftReference to the object
SoftReference<Object> softRef = new SoftReference<>(heavyObject);

// Releasing the strong reference
heavyObject = null;

// At any moment, check if the object is available
if (softRef.get() != null) {
    // Object is not yet collected
    System.out.println("Object is still available through SoftReference");
} else {
    // Object has been collected by the garbage collector
    System.out.println("Object was collected");
}

Example of using WeakReference:

// Object being referenced
Object lightweightObject = new Object();

// Creating a WeakReference to the object
WeakReference<Object> weakRef = new WeakReference<>(lightweightObject);

// Releasing the strong reference
lightweightObject = null;

// The garbage collector can collect the object at any moment
if (weakRef.get() != null) {
     System.out.println("Object is still available through WeakReference");
} else {
     System.out.println("Object was collected");
}

Thus, the key difference lies in the garbage collection priority: SoftReference provides a higher "priority" for retaining the object when there is free memory, whereas WeakReference offers only a weak link that does not prevent garbage collection at any moment.