Sobes.tech
Junior — Middle

Explain what a weak reference is and in what cases it is used in programming.

sobes.tech AI

Answer from AI

A weak reference is a reference to an object that does not prevent it from being garbage collected. If only weak references to an object exist, the garbage collector can free the memory occupied by that object.

It is used in cases where you need to hold a reference to an object but do not want to prevent its deletion, for example:

  • Caching objects so as not to keep them in memory longer than necessary.
  • References to listeners or event handlers to avoid memory leaks.

In Java, weak references are implemented through the WeakReference class from the java.lang.ref package.

Example:

WeakReference<MyObject> weakRef = new WeakReference<>(new MyObject());
// If there are no more strong references to MyObject, the object can be collected by the garbage collector