Using various reference types in Java

I recently played with soft, weak, and phantom reference types in Java and wondered if there were any options for them that I hadn't come across. I used them in the past for different things, and they have always been categorized as follows:

  • Using phantom links instead of finalizers - I prefer this, since there is a chance of resurrecting a dead object.
  • Using weak links in a hash map to store the display of an object => where the display should only be in place if the object exists elsewhere (useful when you need to add additional information to an object in the library, for example, whose source can't be changed )
  • Using soft links for caching (it works much better than weak links because the JVM supports them much longer and only allows it if it seems to be necessary.)

However, only 3 is used there, and I dare to suggest that they may be useful, for which I have never encountered. All suggestions are welcome!

+4
source share
1 answer

Two strange ideas:

  • You can use a soft link to find out that you have little memory, and manually free some caches that themselves cannot use soft links.
  • You can use the weak link to find out when the GC is running, which can be useful if you experience strange program pauses that may or may not be related to the GC.

IMHO, in some (rare) cases, weak links may be better for caching, for example, you can weakly refer to values ​​that are unlikely to be necessary again as soon as they are removed from structures using them (i.e. they become very unreachable) . Moreover, there is a serious bug in the JVM regarding soft links, which may make you do this.

+1
source

Source: https://habr.com/ru/post/1336399/


All Articles