java.lang.ref.WeakReference class is used to create an object that wraps another object - innerObject. The object it wraps can be removed from memory by Garbage Collector (GC) if it is no longer being used somewhere else stronger than GC.
For easy understanding, see the code below:
In the above code we have innerObject object, which is used as a parameter to create weakRef object, or in other words innerObject is being used by weakRef.
In common sense, if an object is in use somewhere, it is useful and cannot be removed from memory. However, WeakReference is a special class, which is considered weaker than Garbage Collector (GC). Object wrapped in a WeakReference can still be removed from memory by GC if it is no longer being used somewhere else stronger than GC.
In the above example we call System.gc() method to tell Garbage Collector to work. This request has no immediate effect. Basically, GC is a sophisticated and complex machine that works automatically and you can only interfere with it in a limited way.
In the next example, we won't actively call System.gc() method, but GC will still remove the object wrapped inside WeakReference after a while if it's no longer being used somewhere else stronger than GC.
All methods of WeakReference are inherited from parent class.
2- Primitive Inner Object
A primitive value is not a reference although it can be written like a reference. So if it is wrapped inside a WeakReference it will not be removed from memory by GC.
3- Non-Primitive Inner Object
If an object is created by the "new" operator and wrapped inside a WeakReference, it will be removed from memory by GC if it is no longer being used somewhere else stronger than GC.
The object wrapped inside a WeakReference acts as a diner in a restaurant. When diners finish eating, they are ready to leave the table even if at that time the restaurant has many empty tables. SoftReference is a bit different from WeakReference, diners can sit back and only leave if the restaurant has no more free tables or the number of available free tables is less than a safe value.
4- WeakReference(T, ReferenceQueue<? super T>)
Create a WeakReference object that wraps innerObject object. If innerObject is removed from memory by GC, this WeakReference object will be added to the queue.
Next, we need a more complex example. In this example, Employee objects are added to a Company. And a List object containing a list of weak references to each Employee object. As long as Company stores Employee objects, they will not be removed from memory by GC.