Optimization-using soft references and weak references

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.

1, if an object has only soft references, enough memory, will not be recycled, not enough memory, on the recovery. 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 .

2. If an object has only weak references, it will be recycled . However, because the garbage collector is a low-priority thread, it is not necessarily quick to discover objects that have only weak references.

Common denominator: Both soft and weak references can be used in conjunction with a reference queue. Is recycled, the Java Virtual Opportunity adds the reference to the associated reference queue (Referencequeue).

Fundamental difference: only has the soft, the memory is not enough to recover, only has the weak, meets on the recovery.

Application: When dealing with large-memory, long-period objects, you can apply soft and weak reference techniques as much as possible.

Several classes are available in the Java.lang.ref package:

SoftReference class, soft reference

WeakReference class Weak references

Phantomreference class, virtual Reference

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.

Weak references are used in a similar way to soft references.

The following is an example of using a soft reference as a detailed explanation.

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) {

Strongly-referenced bitmap objects

Bitmap Bitmap = bitmapfactory.decodefile (path);

Soft-referenced bitmap objects

softreference<bitmap> Softbitmap = new softreference<bitmap> (BITMAP);

Add the object to the map so that it is cached

Imagecache.put (path, softbitmap);

}

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);

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:

When to use soft references, when do you use weak references?

Personal opinion,

1. If you just want to avoid the occurrence of 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.

2, there is 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 uses Referencequeue to implement this mechanism.

Optimization-using soft references and 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.