"Reprint" Java 7 Foundation-strong references, weak references, soft references, virtual references

Source: Internet
Author: User

The so-called memory leak, is actually the object in the time of the recovery is not properly recycled, the memory of these wild pointers. So it's important to understand these kinds of citation patterns and use it with the Great God's blog.

Reprint: http://blog.csdn.net/mazhimazh/article/details/19752475

Reference type

Garbage collection Time

Use

Survival time

Strong references

would never

General state of the object

Termination when JVM stops running

Soft references

When there is not enough memory

Object Cache

Terminate when memory is low

Weak references

At garbage collection time

Object Cache

Abort after GC run

Virtual reference

Unknown

Unknown

Unknown

1. Strong citation (Strongreference)

Strong references are the most commonly used references. If an object has a strong reference, the garbage collector will never recycle it. As follows:

[Java]View Plaincopyprint?
    1. Object o=new Object (); //strong references

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. If not, use the following method to weaken the reference, as follows:

[Java]View Plaincopyprint?
    1. o=null; //help garbage collector Reclaim this object

Explicitly setting o to null, or exceeding the life cycle of an object, the GC considers that the object does not have a reference and can then reclaim the object. The exact time to collect this depends on the GC algorithm.

Example:

[Java]View Plaincopyprint?
    1. Public Void Test () {
    2. Object o=new Object ();
    3. //Omit other actions
    4. }

There is a strong reference inside a method that is stored in the stack, and the real reference content (Object) is stored in the heap. When this method runs and exits the method stack, references to references do not exist, and the object is recycled.

However, if this o is a global variable, you will need to assign NULL when you do not use this object, because a strong reference is not garbage collected.

Strong references have very important uses in practice, for example, a ArrayList implementation source code:

[Java]View Plaincopyprint?
  1. Private transient object[] elementdata;
  2. Public void Clear () {
  3. modcount++;
  4. /Let GC do it work
  5. For (int i = 0; i < size; i++)
  6. Elementdata[i] = null;
  7. size = 0;
  8. }

A private variable elementdata array is defined in the ArrayList class, and you can see that the contents of each array are assigned NULL when the calling method empties the array. Unlike Elementdata=null, strong references persist to avoid re-allocating memory when adding elements such as subsequent calls to add (). Using methods such as the clear () method to free memory is particularly useful for the type of reference that is stored in the array, which frees up memory in a timely manner.

2. Soft Reference (SoftReference)

If an object has only soft references, enough memory space is available, the garbage collector does not recycle 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.

[Java]View Plaincopyprint?
    1. String str=new String ("abc"); //strong references
    2. softreference<string> softref=new softreference<string> (str); //Soft reference

When memory is low, it is equivalent to:

[Java]View Plaincopyprint?
    1. If (JVM. Insufficient memory ()) {
    2. str = null; //Convert to Soft reference
    3. System.GC (); //garbage collector for recycling
    4. }

Virtual references have important applications in practice, such as the browser's Back button. When you press back, will the page content that is displayed on the back of this fallback be re-requested or removed from the cache? This depends on the specific implementation strategy.

(1) If a Web page is recycled at the end of the browse, then pressing back to view the previously browsed page needs to be rebuilt

(2) If you store your browsed pages in memory, it can cause a lot of wasted memory and even memory overflow.

You can then use soft references

[Java]View Plaincopyprint?
  1. Browser prev = new Browser (); //Get page to browse
  2. softreference sr = New SoftReference (prev); //After browsing is complete, set to soft reference
  3. if (sr.get () =null) {
  4. Rev = (Browser) sr.get (); //has not been recycled by the collector, directly obtained
  5. }else{
  6. prev = new Browser (); //Due to memory constraints, the soft-referenced objects are recycled
  7. sr = New SoftReference (prev); //re-build
  8. }

This will be a good solution to the actual problem.

A soft reference can be used in conjunction with a reference queue (Referencequeue), and if the object referenced by the soft reference is reclaimed by the garbage collector, the Java Virtual machine will add the soft reference to the reference queue associated with it.

3. Weak references (WeakReference)

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.

[Java]View Plaincopyprint?
    1. String str=new String ("abc");
    2. weakreference<string> abcweakref = new weakreference<string> (str);
    3. str=null;

When the garbage collector is scanned for recycling, it is equivalent to:

[Java]View Plaincopyprint?
    1. str = null;
    2. System.GC ();

If this object is used occasionally and wants to be available at any time when it is used, but does not want to affect the garbage collection of this object, then you should use Weak Reference to remember this object.

The following code causes STR to become a strong reference again:

[Java]View Plaincopyprint?
    1. String ABC = abcweakref.get ();

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.

When you want to refer to an object, but this object has its own life cycle, you do not want to intervene in the life cycle of this object, you are using weak references.

This reference does not have any additional impact on the object's garbage collection judgment.

[Java]View Plaincopyprint?
  1. Public class Referencetest {
  2. private static referencequeue<verybig> RQ = new referencequeue<verybig> ();
  3. public static void Checkqueue () {
  4. reference<?  extends verybig> ref = null;
  5. While (ref = Rq.poll ()) = null) {
  6. if (ref! = null) {
  7. System.out.println ("in queue:" + ((verybigweakreference) (ref)). ID);
  8. }
  9. }
  10. }
  11. public static void Main (String args[]) {
  12. int size = 3;
  13. linkedlist<weakreference<verybig>> weaklist = new Linkedlist<weakreference<verybig>> ()  ;
  14. For (int i = 0; i < size; i++) {
  15. Weaklist.add (Newverybigweakreference (new Verybig ("Weak" + i), RQ));
  16. System.out.println ("Just created weak:" + weaklist.getlast ());
  17. }
  18. System.GC ();
  19. try { //under rest for a few minutes and let the garbage collection thread above run complete
  20. Thread.CurrentThread (). Sleep (6000);
  21. } catch (Interruptedexception e) {
  22. E.printstacktrace ();
  23. }
  24. Checkqueue ();
  25. }
  26. }
  27. Class Verybig {
  28. public String ID;
  29. //Occupy space for the thread to recycle
  30. byte[] B = new byte[2 * 1024];
  31. Public Verybig (String id) {
  32. this.id = ID;
  33. }
  34. protected Void Finalize () {
  35. System.out.println ("finalizing Verybig" + ID);
  36. }
  37. }
  38. Class Verybigweakreference extends Weakreference<verybig> {
  39. public String ID;
  40. Public verybigweakreference (Verybig big, referencequeue<verybig> RQ) {
  41. super (big, RQ);
  42. this.id = big.id;
  43. }
  44. protected Void Finalize () {
  45. System.out.println ("finalizing verybigweakreference" + ID);
  46. }
  47. }

The result of the final output is:

[Java]View Plaincopyprint?
  1. Just created weak:com.javabase.reference.VeryBigWeakReference@1641c0
  2. Just created weak:com.javabase.reference.VeryBigWeakReference@136ab79
  3. Just created weak:com.javabase.reference.VeryBigWeakReference@33c1aa
  4. Finalizing Verybig Weak 2
  5. Finalizing Verybig Weak 1
  6. Finalizing Verybig Weak 0
  7. In Queue:weak 1
  8. In Queue:weak 2
  9. In Queue:weak 0



4. Virtual Reference (Phantomreference)

"Virtual Reference", as the name implies, is a dummy, unlike several other references, a virtual reference does not determine the object's life cycle. If an object holds only virtual references, it can be reclaimed by the garbage collector at any time, just as there are no references.

Virtual references are primarily used to track activities that objects are reclaimed by the garbage collector. 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.

5. Summary

The level of JAVA4 references is from highest to lowest:

Strong references > Soft references > Weak references > virtual references

Take a look at the differences between them in garbage collection:

When the garbage collector recycles, some objects are reclaimed and some are not recycled. The garbage collector marks the surviving object from the root object, and then reclaims some unreachable objects and some referenced objects, and if you are not familiar with this, refer to the following article:

Portal: Java Memory management http://blog.csdn.net/mazhimazh/article/category/1907599

Use the form to illustrate, as follows:

Reference type

Garbage collection Time

Use

Survival time

Strong references

would never

General state of the object

Termination when JVM stops running

Soft references

When there is not enough memory

Object Cache

Terminate when memory is low

Weak references

At garbage collection time

Object Cache

Abort after GC run

Virtual reference

Unknown

Unknown

Unknown

"Reprint" Java 7 Foundation-strong references, weak references, soft references, virtual 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.