Why do I need different types of links in Java?


I'm deepening my knowledge of Java. I came across an article about link types. I realized that there are 4 types of links:

  1. Strong reference
  2. Weak Reference
  3. Soft Reference
  4. Phantom Reference

I don't know if I understood correctly, so I ask you to correct it.

1 Type strong link (Strong reference)

Object object = new Object();//создал обьект 
object = null;//теперь может быть собран сборщиком мусора

2 Type weak link (Weak Reference)

// какой-то объект
Object object= new Object ();

// слабая ссылка на него
WeakReference<Object > weakStudent = new WeakReference<Object >(object);

// теперь объект Object  может быть собран сборщиком мусора
object= null;

3 Type soft link (Soft Reference)

// какой-то объект
Object object= new Object ();

// слабая ссылка на него
SoftReference<Object > softStudent = new SoftReference<Object >(object)

// теперь объект Student может быть собран сборщиком мусора
// но это случится только в случае сильной необходимости JVM в памяти
object= null;

4 Type phantom link (didn't understand anything about it)

Author: Kromster, 2018-02-09

1 answers

More or less described in the package documentation java.lang.ref:

Soft references are for implementing memory-sensitive caches, weak references are for implementing canonicalizing mappings that do not prevent their keys (or values) from being reclaimed, and phantom references are for scheduling post-mortem cleanup actions. Post-mortem cleanup actions can be registered and managed by a Cleaner.

Read more and in Russian, in descending order stiffness:

  • Strong , they are also ordinary, are needed to point to objects that must necessarily remain in memory all the time that these references to it exist. If it doesn't add up, get OutOfMemoryError.
  • Soft references are useful for caches that are sensitive to the available amount of RAM. Objects on them can be cleared, but only if necessary. For example, if you need to create more objects with strong links, but there is already nowhere, it is better to free up the cache and slow down the work, than to drop the process completely.
  • Weak references are useful for mapping objects to something without keeping them from being stripped when they are no longer needed (a la Map<Ключ, WeakRef<Значение>>). They do not affect the ability to clean up in any way at all, weak links will be cleared the next time the collector is run.
  • Phantom references occur when an object is already recognized as garbage, finalized, and in the process of being cleaned up, which can be found with using the class Cleaner and perform some actions of your own at this time.

Plus the general rule: the policy of cleaning up for a certain object and clearing references to it is determined by the most rigid of all references that point to it.


Glossary of not-so-obvious translations:

  • reclaim, reclaim-reclaim, reclamation
  • clear - clear
 12
Author: , 2018-02-09 15:09:06