Using different links you can get a great speed of the garbage collector or are links used for other purposes?
The difference is not in speed, the difference is in how the garbage collector will work with the object by reference.
SoftReference is the strongest of all the listed links. If there are no more normal references to the object, but only
SoftReference , the object will not be eaten by the garbage collector until there is really a shortage of memory.
A good example of using such links is the cache of large pictures in memory. If the memory is exhausted, the image will be thrown away by the garbage collector, and you can re-read it from the disk when you need it again.
WeakReference weaker: it does not additionally increase the lifetime of the object to which it refers, and if the object has nothing more than weak references, the garbage collector can remove it when it pleases.
A good example of use for such links is to add additional information about an object. To do this, you keep in your container not the object itself, but only the
WeakReference on it, along with the necessary information, thus you do not prevent the object from dying on time and do not change the properties of the rest of the program.
WeakReference on a still-living object, you can get a real ("strong") link, and prevent the garbage collector from eating this object. Having a strong link, you can work with the object as usual.
PhantomReference even weaker. Not only does it not protect the object from cleaning, it does not even give an opportunity to get a strong link. You can only find out that the object is going to die, and take some sort of cleaning action; prevent the death of the object you can not.
When creating a
WeakReference you can, and when creating a
PhantomReference must specify
ReferenceQueue (although you can specify
null , this is usually meaningless). After the object is cleared by the garbage collector, the link falls into the
ReferenceQueue you specified.
For non-phantom references, when added to a queue, the finalizer is already completed and the object's memory has already been released, but for phantom references, the addition occurs after calling the finalizer before the memory is cleared. You can essentially not declare an expensive finalizer, but rather use a phantom reference from the queue in order to release the associated resources yourself. (For this, you cannot use the object itself,
PhantomReference strong link to it cannot be obtained from the phantom link; but you can inherit from
PhantomReference to add the necessary information to the link object.)
Another difference, as @gstackoverflow suggests in the comments, is that you must clear the phantom link manually, otherwise the object will remain (phantom) reachable. Only after that the object will be permanently deleted.
Speed control fail. But more efficient use of memory - yes.
PhantomReference you hardly have to use.
Read about them .