How to use weakhashmap

How to use weakhashmap

preface:

  when learning weakhashmap, I learned that if the key in the map is only referenced by the map itself, the entry corresponding to the key will be cleared. Looking at the source code of weakhashmap, it is found that the entry inherits the WeakReference class, and when instantiating the entry object, all keys will save weak references to the actual object by calling the super (key, queue) method. In fact, weak references also need to pass in a strong reference of an object as a parameter during construction. For example:

  this is also the difference between HashMap and weakhashmap. The key of HashMap is a strong reference to the actual object.

  the feature of weak reference is that when the GC thread finds that an object has only a weak reference to it, it will destroy it and reclaim memory. The WeakReference will also be added to the reference queue.

  after understanding the relevant concepts, I'm curious about the practical application of weakhashmap. Then I found that in the source code of tomcat, weakhashmap will be used to implement caching.

  there are two maps of Eden and longterm in the source code. If you know something about the JVM heap, you can guess that Tomcat uses concurrenthashmap and weakhashmap for generation caching. In the put method, when inserting a K-V, first check whether the capacity of Eden cache is exceeded. If there is no super, it will be directly put into the Eden cache. If it is, lock the longterm and put all K-V in Eden into the longterm. Then empty Eden and insert k-v. In the get method, it is also a priority to find the corresponding V from Eden. If not, it will enter the longterm cache. After finding it, it will be added to the Eden cache and returned.

  through this design, relatively common objects can be found in Eden cache, Those that are not commonly used (objects that may be destroyed) will enter the longterm cache. When there is no other reference to the actual object of the key of the longterm, GC will automatically recycle the actual object pointed to by the weak reference in the heap, and the weak reference will enter the reference queue. Longterm calls the expungestaleentries() method to traverse the weak reference in the reference queue and clear the corresponding entry, No waste of memory space.

If you have any questions, please leave a message or go to the community of this site for exchange and discussion. Thank you for reading. I hope it can help you. Thank you for your support to this site!

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>