Soft references, weak references, Java, code buffs

Source: Internet
Author: User

  Java from JDK1.2 version begins by dividing 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.

Here are some highlights of soft and weak references.

If an object has only soft references, the garbage collector will not recycle it if there is enough memory space ; If there is not enough memory space, the memory of these 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,theJava The virtual machine will add the soft reference to the reference queue associated with it.

If an object has only weak references, when the garbage collector thread scans, an object with only a weak reference will be 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 also be used in conjunction with a reference queue (referencequeue) , and if the object referenced by the weak reference is garbage collected,theJava virtual machine will add the weak reference to the reference queue associated with it.

The fundamental difference between a weak reference and a soft reference is that an object with only a weak reference has a shorter life cycle and may be recycled at any time. Objects that only have soft references are recycled only when there is not enough memory, and are usually not recycled when there is enough memory.

Several classes are available in the java.lang.ref Package: Thesoftreference class,theweakreference class, and the phantomreference classes, which represent soft references, weak references, and virtual references, respectively. the referencequeue class represents a reference queue, which can be used in conjunction with these three reference classes in order to track the activity of the object referenced by the Java virtual machine.

In the development of Android application, in order to prevent memory overflow, we can apply soft reference and weak reference technique when dealing with some objects that occupy large memory and have long declaration period.

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 HashMapand save the soft reference object.

Private map<string, softreference<bitmap>> Imagecache = new hashmap<string, Softreference<bitmap >> ();

To define a method, save The soft reference of Bitmap to HashMap.

public void addbitmaptocache (String  path)  { 

//  bitmap

bitmap bitmap =  Bitmapfactory.decodefile (path);  

//  soft-referenced Span style= "font-family:arial;" >bitmap

softreference<bitmap>  softBitmap = new SoftReference<Bitmap> (Bitmap);  

// < Span style= "font-family: the song Body;" > Add the object to map

imagecache.put (path, softbitmap);  

}&NBSP;

When obtained, the Bitmap object can be obtained by SoftReference the get () method .

Public Bitmap Getbitmapbypath (String path) {

to take a soft-referenced Bitmap object from the cache

softreference<bitmap> Softbitmap = Imagecache.get (path:http://www.561.cn);

determine if a soft reference exists

if (Softbitmap = = null) {

return null;

}

Remove the Bitmap object, if the Bitmap is recycled due to insufficient memory , it will get empty

Bitmap Bitmap = Softbitmap.get ();

return bitmap;

}

With soft references, the memory space of these cached picture resources can be freed up before the OutOfMemory exception occurs, preventing the memory from reaching the upper limit and preventing Crash from occurring.

It is important to note that in the garbage collector the java softreference provided by the class. get java java get null null nullpointerexception

Experience Sharing:

When to use soft references, when do you 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, Weakhashmapis 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 uses referencequeue to implement this mechanism.

  

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.