Android Learning note _78_ using soft references and weak references in Android development to prevent memory overflow

Source: Internet
Author: User

In effective Java 2nd Edition, 6th, "eliminate outdated object references," mentions that while Java has a garbage collection mechanism, you should be wary of memory leaks if you are managing memory yourself, such as Object pooling, Outdated objects in the cache can cause problems with memory leaks. The book also mentions that Weakhashmap can be used as a cache container to effectively solve this problem.    I have encountered a similar problem before, but have not contacted the "weak reference" related problems, and then consulted some information. Java Theory and Practice: using weak references to block memory leaks also points to memory leaks that occur when using global map as a cache container, describes how to use the Hprof tool to find memory leaks, and analyzes how to use weak references to prevent memory leaks. The key code of Weakhashmap is also analyzed, which is of great reference value.    However, this article misses a few important points to be aware of, but also lacks a test code, this article will make appropriate additions. 1, four references, starting with the JDK1.2 version, divide the object's references into four levels, giving the program more flexibility in controlling the object's life cycle.    These four levels are high to low in order: Strong references, soft references, weak references, and virtual references. Strong references: Usually when we program, for example: Object Object=New Object (); That object is a strong reference. If an object has a strong reference, it is similar to essential necessities, and the garbage collector will never recycle it.    When there is not enough memory space, the Java virtual Machine prefers to throw a outofmemoryerror error, which causes the program to terminate abnormally, and does not rely on random recycling of strongly referenced objects to resolve out-of-memory issues. Soft Reference (SoftReference): If an object has only soft references, it is similar to a living thing that can be used. If the memory space is sufficient, the garbage collector does not reclaim it, and if the memory space is insufficient, the memory of those objects is reclaimed. The object can be used by the program as long as it is not reclaimed by the garbage collector. Soft references can be used to implement memory-sensitive caches.    A soft reference can be used in conjunction with a reference queue (Referencequeue), and if the object referenced by the soft reference is garbage collected, the Java Virtual machine will add the soft reference to the reference queue associated with it. Weak references (WeakReference): If an object has only weak references, it is similar to a living thing that can be used. The difference between a weak reference and a soft reference is that an object with only a weak reference has a shorter life cycle. As the garbage collector thread scans the area of memory it governs, once an object with only a weak reference is found, its memory is reclaimed, regardless of whether the current memory space is sufficient or not.  However, because the garbage collector is a low-priority thread, it is not necessarily quick to discover objects that have only weak references.    A weak reference can be used in conjunction with a reference queue (Referencequeue), and if the object referenced by the weak reference is garbage collected, the Java virtual machine adds the weak reference to the reference queue associated with it. Virtual Reference (phantomreference): "Virtual Reference" as the name implies, is the form of a dummy, and several other references are different, the virtual reference does not determine the life cycle of the object. If an object holds only virtual references, it can be garbage collected at any time, just as there are no references. Virtual references are primarily used to track the activities of objects that are garbage collected. One difference between a virtual reference and a soft reference and a weak reference is that the virtual reference must be used in conjunction with the reference queue (Referencequeue). When the garbage collector prepares to reclaim an object, if it finds that it has a virtual reference, it will add the virtual reference to the reference queue associated with it before reclaiming the object's memory. The program can see if the referenced object is going to be garbage collected by judging whether the reference queue has been added to the virtual reference. If the program finds that a virtual reference has been added to the reference queue, it can take the necessary action before the memory of the referenced object is recycled.
The following is an example of using a soft reference as a detailed explanation. Weak references are used in a similar way to soft references. Suppose our app uses a lot of default images, such as the default avatar in the app, the default game icon, and so on, which can be used in many places. If you read the picture every time, the slow speed of reading the file requires hardware operation, which results in lower performance. So we're thinking about caching the images and reading them directly from memory when needed. However, because the picture occupies a large memory space, caching many images requires a lot of memory, it is likely to be more prone to outofmemory exceptions. In this case, we can consider using soft-referencing techniques to avoid this problem. First, define a hashmap and save the soft reference object. Private map<string, softreference<bitmap>> Imagecache = new hashmap<string, Softreference<bitmap >> ();  again to define a method to save the soft reference of bitmap to HashMap.     public void Addbitmaptocache (String path) {       //strongly referenced bitmap object       & nbsp Bitmap Bitmap = bitmapfactory.decodefile (path);       //Soft Reference Bitmap object         Soft reference<bitmap> Softbitmap = new Softreference<bitmap> (Bitmap);       // Add the object to the map to make it cache         imagecache.put (path, softbitmap);   }      When obtained, the bitmap object can be obtained by softreference the Get () method.     Public Bitmap Getbitmapbypath (String path) {      //Bitmap object that takes soft references from cache         softreference<bitmap> softbitmap = Imagecache.get ( Path);       //Determine if there is a soft reference         if (Softbitmap = = null) {      &N Bsp     return null;       }       //Remove Bitmap object, if due to insufficient memory bitmap is recycled, will get empty &NB Sp       Bitmap Bitmap = Softbitmap.get ();        return bitmap;   }  using soft references Later, before the outofmemory exception occurs, the memory space of these cached picture resources can be freed up, thus avoiding the upper limit of memory and avoiding crash occurrence. It should be noted that the Get method provided by the SoftReference class returns a strong reference to the Java object before the garbage collector reclaims the Java object, and once the garbage thread reclaims the Java object, the Get method returns NULL. So in the code that gets the soft reference object, be sure to determine whether it is null in case the NullPointerException exception causes the application to crash.   Experience sharing: When to use soft references, when to use weak references? Personally, if you just want to avoid outofmemory exceptions, you can use soft references. If you are more concerned about the performance of your application and want to reclaim some objects that occupy large memory as soon as possible, you can use weak references. There is also can be based on whether the object is often used to judge. If the object is likely to be used frequently, use soft references as much as possible. If the object is more likely to be used, a weak reference can be used. In addition, Weakhashmap is similar to the weak reference function. Weakhashmap for a given key, the presence of its mapping does not prevent the garbage collector from reclaiming the key, and its entries are effectively removed from the map after recycling. Weakhashmap using REFERENCEQUeue implementation of this mechanism.  
Map<string, softreference<bitmap>> iconcache=NewHashmap<string, softreference<bitmap>>();if(Iconcache.containskey (iconname)) {SoftReference<Bitmap> Softref =Iconcache.get (iconname);if(Softref! =NULL) {Bitmap Bitmap=softref.get ();if(Bitmap! =NULL) {Iv_book.setimagebitmap (bitmap); } Else{LoadImage (Iv_book, book, iconname); }}} Else{LoadImage (Iv_book, book, iconname);} Iconcache.put (Iconname,NewSoftreference<bitmap> (Bitmap));

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

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.