Câu hỏi phỏng vấn Java
Câu hỏi

What's the difference between SoftR...

Câu trả lời

In Java, SoftReference and WeakReference are both classes that provide a way to reference objects without preventing them from being garbage collected, but they do so with different levels of strength and are used for different purposes.

A WeakReference in Java is a reference that does not prevent its referent from being made eligible for garbage collection. An object that is only weakly referenced (meaning the strongest references to it are WeakReferences) will be discarded at the next garbage collection cycle if no strong references exist. This makes WeakReference suitable for storing metadata or as keys in a WeakHashMap, where the entry in the map is removed automatically once the key is no longer in ordinary use elsewhere[1][2][3][5][7].

On the other hand, a SoftReference is similar to a WeakReference but with a softer constraint. It is less eagerly collected by the garbage collector, meaning that objects that are softly referenced will generally remain in memory longer, as long as there is sufficient memory available. The garbage collector is more likely to clear a SoftReference only when it needs memory urgently. This behavior makes SoftReference suitable for implementing caches, where you want the object to stay in memory as long as possible to avoid expensive recomputation or reloading, but still allow it to be collected if memory is needed[1][2][3][4][5].

In summary, the key differences are:

  • Garbage Collection Sensitivity: WeakReference objects are cleared by the gar...
expert

expert

Gợi ý câu hỏi phỏng vấn

junior

When does an Object becomes eligible for Garbage Collection in Java ?

junior

What are the Data Types supported by Java? What is Autoboxing and Unboxing?

senior

What is Double Brace initialization in Java?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào