Soft references, weak references, Java

Source: Internet
Author: User

starting with the JDK1.2 version, Java is 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 does not recycle it if there is enough memory space, and the memory of those objects is reclaimed if there is insufficient memory space. 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.

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, the Java 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: The SoftReference class, the WeakReference class, and the Phantomreference class, which represent soft, weak, 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 hashmap and 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) {

Span style= "FONT-SIZE:14PX;" >       //strongly referenced bitmap object

         Bitmap Bitmap = bitmapfactory.decodefile (path);

       //Soft-referenced bitmap object

Span style= "FONT-SIZE:14PX;" >        softreference<bitmap> softbitmap = new SoftReference<Bitmap > (bitmap);

       //Add the object to the map so that it caches

Span style= "FONT-SIZE:14PX;" >        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 the cache

softreference<bitmap> softbitmap = imagecache.get (path);

//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 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:

Personally, you can use a soft reference if you just want to avoid the occurrence of a outofmemory exception. 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.

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.