Memory overflow analysis caused by careless use of Weakhashmap

Source: Internet
Author: User
Tags garbage collection
Inadvertent use of weakhashmap leads to memory overflow analysis:   There are several applications in the community that use similar locker code, essentially extracted from the messaging system engine, except that the ID in the locker used in the message is of type long. The ID is automatically converted to long by the JVM as the key is put into the map, so that the key in Weakhashmap is referenced by the value. If you use string as an ID, the value in the map refers to its own key, which causes the JVM to not clear the entry in the Weakhashmap based on whether the key is still referenced. The results can be clearly observed through the following test code.   public class locker {    private static WeakHashMap< String, locker> lockermap = new weakhashmap<string, locker> ();     private final String id;     private locker (string id)  {         this.id= id;     }     public synchronized static locker acquire (string id)  {        Locker locker =  Lockermap.get (key);         if  (locker == null)  { &Nbsp;          locker = new locker (ID);             lockermap.put (Id, locker); //Problem code, led to the Entry.key = = Entry.value.id             // Lockermap.put (new string (ID),  locker); //This is a modified way to ensure that key in the WEAKHASHMAP is not referenced directly or indirectly by value          }         return locker; &NBSP;&NBSP;&NBSP;&NBSP}     public string getid ()  {         return this.id; &NBSP;&NBSP;&NBSP;&NBSP}     public static int getsize ()  {         return lockermap.size (); &NBSP;&NBSP;&NBSP;&NBSP}}   public class lockertest extends testcase {     public void testlocker ()  {        for  (int  i = 0; i < 10000000; i++)  {             locker.acquire ("abc"  + i);             if  (i % 10000 ==  0)  {                &NBSP;SYSTEM.GC ();                  System.out.println (Locker.getsize ());     //output the size of the map after garbage collection              }              &NBSP}}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.