How to effectively avoid OOM in Java: good at using soft references and weak references

Source: Internet
Author: User

Many may be familiar with the OOM (OutOfMemory) error. How can this problem be effectively solved? Today, let's talk about how to use soft references and weak references to effectively solve the OOM problem in the program. The following is the directory outline of this article: 1. understand the concepts of strong references, soft references, weak references, and virtual references. further understanding of soft references and weak references 3. I would like to thank you for your understanding and criticism on how to use soft references and weak references to solve the OOM problem. I. understand the concepts of strong references, soft references, weak references, and virtual references in Java, although programmers do not need to manually manage the object lifecycle, however, if you want some objects to have a certain life cycle (for example, if the memory is insufficient, JVM automatically recycles some objects to avoid the OutOfMemory error), soft references and weak references are required. Since Java SE2, four types of references are provided: strong reference, soft reference, weak reference, and virtual reference. Java provides these four reference types for two main purposes: first, it allows programmers to determine the lifecycle of some objects through code; second, it is conducive to JVM garbage collection. The following describes the concepts of these four types of references: 1. strongReference a strong reference is a common reference in program code. For example, the objects and str in the following code are strongly referenced: object Object = new object (); string str = "hello"; as long as an object has a strong reference associated with it, JVM will not recycle this object, even if the memory is insufficient, JVM would rather throw an OutOfMemory error than reclaim this object. For example, the following code: public class Main {public static void main (String [] args) {new Main (). fun1 () ;}public void fun1 () {Object object = new Object (); Object [] objArr = new Object [1000] ;}} when running to Object [] objArr = new Object [1000];, if the memory is insufficient, the JVM will throw an OOM error and will not recycle the objects pointed to by the object. However, it should be noted that after fun1 is run, the object and objArr do not exist, so the objects they point to will be recycled by JVM. If you want to interrupt the association between a strong reference and an object, you can explicitly assign the reference value to null. In this way, the JVM will reclaim the object at the appropriate time. For example, in the clear method of the Vector class, the reference value is null to clean up: View Code 2. softReference is used to describe some useful but not necessary objects. lang. ref. softReference class. For objects associated with soft references, the JVM recycles the object only when the memory is insufficient. Therefore, this can be used to solve the OOM problem, and this feature is suitable for Cache: for example, webpage cache and image cache. Soft reference can be used together with a ReferenceQueue. If the referenced object of soft reference is recycled by JVM, the soft reference will be added to the reference queue associated with it. The following is an example: import java. lang. ref. softReference; public class Main {public static void main (String [] args) {SoftReference <String> sr = new SoftReference <String> (new String ("hello"); System. out. println (sr. get () ;}} 3. weakReference is also used to describe non-essential objects. When JVM garbage collection is performed, objects associated with weak references will be recycled no matter whether the memory is sufficient or not. In java, it is represented by the java. lang. ref. WeakReference class. The following is an example: import java. lang. ref. weakReference; public class Main {public static void main (String [] args) {WeakReference <String> sr = new WeakReference <String> (new String ("hello"); System. out. println (sr. get (); System. gc (); // notify the JVM gc to recycle the System. out. println (sr. get () ;}} the output result is: The second output result of View Code is null. This indicates that as long as JVM garbage collection is performed, objects associated with weak references will be recycled. However, it should be noted that the objects associated with weak references here refer to only weak references associated with them. If there is strong references associated with them at the same time, this object will not be recycled during garbage collection (as is the case with soft references ). A weak reference can be used together with a ReferenceQueue. If the referenced object of a weak reference is recycled by JVM, this soft reference will be added to the reference queue associated with it. 4. Different from the previous soft references and weak references, the virtual reference does not affect the object lifecycle. Java. lang. ref. PhantomReference class is used in java. If an object is associated with a virtual reference, the object may be recycled by the garbage collector at any time. Note that the virtual reference must be associated with the reference queue. When the garbage collector is preparing to recycle an object, if it finds that there is a virtual reference, this virtual reference is added to the reference queue associated with it. The program can determine whether the referenced object has been added to the reference queue to check whether the referenced object is to be recycled. If the program finds that a virtual reference has been added to the reference queue, it can take necessary action before the memory of the referenced object is recycled. Import java. lang. ref. phantomReference; import java. lang. ref. referenceQueue; public class Main {public static void main (String [] args) {ReferenceQueue <String> queue = new ReferenceQueue <String> (); phantomReference <String> pr = new PhantomReference <String> (new String ("hello"), queue); System. out. println (pr. get () ;}} 2. to further understand soft references and weak references, we usually use them when writing code. For the other three types of references, soft references and weak references are used most frequently. These two types have similarities and differences. They are used to describe non-essential objects, but soft-referenced associated objects will be recycled only when the memory is insufficient, objects associated with weak references will be recycled during JVM garbage collection. In the SoftReference class, there are three methods, two constructor methods and one get method (WekReference is similar): Two constructor Methods: public SoftReference (T referent) {super (referent); this. timestamp = clock;} public SoftReference (T referent, ReferenceQueue <? Super T> q) {super (referent, q); this. timestamp = clock;} The get method is used to obtain references to objects associated with soft references. if the object is recycled, null is returned. When using soft references and weak references, we can use System. gc () to notify JVM of garbage collection, but note that although a notification is sent, the JVM may not be executed immediately, that is to say, this statement cannot ensure that the JVM will perform garbage collection at this time. III. how to Use soft references and weak references to solve the OOM problem we have discussed the basic knowledge about soft references and weak references, and how to use them to optimize program performance, so as to avoid OOM problems? For example, if an application needs to read a large number of local images and reads images from the hard disk each time, the performance will be seriously affected. However, if all the images are loaded into the memory, it may also cause memory overflow. In this case, soft reference can be used to solve this problem. The design idea is: Use a HashMap to store the ing between the image path and the soft reference associated with the corresponding image object. When the memory is insufficient, JVM automatically recycles the space occupied by these cached image objects, effectively avoiding the OOM problem. It is often used for downloading a large number of images in Android development. The following code is taken from the blog: private Map <String, SoftReference <Bitmap> imageCache = new HashMap <String, SoftReference <Bitmap> (); <br> .... public void addBitmapToCache (String path) {// Bitmap object with strong reference Bitmap bitmap = BitmapFactory. decodeFile (path); // soft referenced Bitmap object SoftReference <Bitmap> softBitmap = new SoftReference <Bitmap> (bitmap); // Add this object to Map to cache imageCache. put (path, softBitmap);} public Bitmap getBitmapByPath (String path) {// obtain the soft referenced Bitmap object SoftReference <Bitmap> softBitmap = imageCache from the cache. get (path); // determines whether soft reference if (softBitmap = null) {return null;} // retrieves a Bitmap object. if Bitmap is recycled due to insufficient memory, an empty Bitmap bitmap = softBitmap will be obtained. get (); return bitmap;} Of course, here we hand over the cache replacement policy to the JVM for execution, which is a relatively simple method. For a more complex cache, We can independently design a class, which involves cache policy issues. For details, refer to the previous blog: cache algorithm (page replacement algorithm) -FIFO, LFU, and LRU

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.