Java GC and ghost reference

Source: Internet
Author: User

Java GC and ghost reference

There are four types of references in Java: strongreference, softreference, weakreference, and phantomreference ),
These four types of references are closely related to GC. Let's look at their definitions and use cases one by one:

1. Strong reference

Strongreference is the default reference implementation of Java. It will survive in JVM for as long as possible. When no object points to it, it will be recycled after GC is executed.

 1 1. @ Test
2 2. Public Void Strongreference (){
3 3. Object referent = New Object ();
4 4.
5 5. /**
6 6. * Create strongreference by assigning a value
7 7. */
8 8. Object strongreference = referent;
9 9.
10 10. assertsame (referent, strongreference );
11 11.
12 12. referent = Null ;
13 13. system. GC ();
14 14.
15 15. /**
16 16. * strongreference will not be recycled after GC
17 17. */
18 18. assertnotnull (strongreference );
19 19 .}
20 @ Test
21 Public Void Strongreference (){
22 Object referent = New Object ();
23
24 /**
25 * Create strongreference by assigning values
26 */
27 Object strongreference = referent;
28
29 Assertsame (referent, strongreference );
30
31 Referent = Null ;
32 System. GC ();
33
34 /**
35 * Strongreference will not be recycled after GC
36 */
37 Assertnotnull (strongreference );
38 }
39

2. weakreference & weakhashmap

Weakreference, as its name implies, is a weak reference. When the referenced object no longer has a strong reference in JVM, weak reference will be automatically recycled after GC.

1. @ Test
2.Public VoidWeakreference (){
3. Object referent =NewObject ();
4. weakreference <Object> weakrerference =NewWeakreference <Object> (referent );
5.
6. assertsame (referent, weakrerference. Get ());
7.
8. referent =Null;
9. system. GC ();
10.
11./**
12. * once there is no strong reference pointing to the referent, the weak reference will be automatically recycled after GC.
13.*/
14. assertnull (weakrerference. Get ());
15 .}

Weakhashmap uses weakreference as the key. Once there is no strong reference to the key, weakhashmap will automatically delete the related entry after GC.

1. @ Test
2.Public Void Weakhashmap () Throws Interruptedexception {
3. Map <object, Object> weakhashmap = New Weakhashmap <object, Object> ();
4. Object key = New Object ();
5. Object value = New Object ();
6. weakhashmap. Put (Key, value );
7.
8. asserttrue (weakhashmap. containsvalue (value ));
9.
10. Key =Null ;
11. system. GC ();
12.
13. /**
14. * Wait for the invalid entries to enter referencequeue so that it will be cleared when the next gettable call is made.
15. */
16. thread. Sleep (1000 );
17.
18. /**
19. * once there is no strong reference to the key, weakhashmap will automatically delete the related entry after GC.
20. */
21. assertfalse (weakhashmap. containsvalue (value ));
22 .}

3. softreference

Softreference has the same features as weakreference. The biggest difference is that softreference retains reference for as long as possible until the JVM memory is insufficient (guaranteed by virtual machines ), this feature makes softreference very suitable for caching applications.

 
1. @ Test
2.Public VoidSoftreference (){
3. Object referent =NewObject ();
4. softreference <Object> softrerference =NewSoftreference <Object> (referent );
5.
6. assertnotnull (softrerference. Get ());
7.
8. referent =Null;
9. system. GC ();
10.
11./**
12. * Soft references will be recycled only before JVM outofmemory, so it is very suitable for cache applications.
13.*/
14. assertnotnull (softrerference. Get ());
15 .}

4. phantomreference

As the main character of this article, phantom reference is very different from weakreference and softreference because its get () method returns NULL forever, which is the origin of its name.

 
1. @ Test
2.Public VoidPhantomreferencealwaysnull (){
3. Object referent =NewObject ();
4. phantomreference <Object> phantomreference =NewPhantomreference <Object> (referent,NewReferencequeue <Object> ());
5.
6./**
7. * The get method of phantom reference always returns NULL
8.*/
9. assertnull (phantomreference. Get ());
10 .}

You may ask how to use a reference that always returns NULL. Pay attention to the second referencequeue parameter when constructing a phantomreference (in fact, weakreference & softreference can also have this parameter ),
The only use of phantomreference is to track when a referent is added to the referencequeue.

5. rererencequeue

When a weakreference starts to return NULL, the object it points to is ready to be recycled. In this case, you can perform some appropriate cleanup work. pass a referencequeue to a reference constructor. When the object is recycled, the virtual opportunity automatically inserts the object into the referencequeue, weakhashmap uses referencequeue to clear entries with no strong reference of the key.

1. @ Test
2. Public Void Referencequeue () Throws Interruptedexception {
3. Object referent = New Object ();
4. referencequeue <Object> referencequeue = New Referencequeue <Object> ();
5. weakreference <Object> weakreference = New Weakreference <Object> (referent, referencequeue );
6.
7. assertfalse (weakreference. isenqueued ());
8. Reference <? Extends Object> polled = referencequeue. Poll ();
9. assertnull (polled );
10.
11. referent = Null ;
12. system. GC ();
13.
14. asserttrue (weakreference. isenqueued ());
15. Reference <? Extends Object> removed = referencequeue. Remove ();
16. assertnotnull (removed );
17 .}

6. phantomreference vs weakreference

Phantomreference has two advantages: First, it allows us to know exactly when objects are deleted from the memory. This feature can be used in some special needs (such as distributed GC, xwork and Google-guice also use phantomreference for cleanup ).

Second, it can avoid some fundamental problems brought about by finalization. the only role of phantomreference mentioned above is to track when the referent will be added to the referencequeue, but weakreference also has corresponding functions, what is the difference between the two?
This is about the Finalize method of the object. This method will be called before GC is executed. If an object is overloaded with the Finalize method and deliberately creates a strong reference in the method, this will cause this GC to fail to recycle this object and possibly
Cause Any GC. The final result is that there are many garbage in JVM but outofmemory. You can avoid this problem by using phantomreference, because phantomreference is recycled after the Finalize method is executed, this means that it is impossible to get the original reference at this time, so the above problems will not occur. Of course, this is a very extreme example and will not happen in general.

7. Comparison

From http://mindprod.com/jgloss/phantom.html

 

Soft vs weak vs phantom references Type purpose use when gced implementing class
strong reference an ordinary reference. keeps objects alive as long as they are referenced. normal reference. Any object not pointed to can be reclaimed. default
soft reference keeps objects alive provided there's enough memory. to keep objects alive even after clients have removed their references (memory-sensitive caches), In case clients start asking for them again by key. after a first GC pass, the JVM decides it still needs to reclaim more space. JAVA. lang. ref. softreference
weak reference keeps objects alive only while they're in use (reachable) by clients. containers that automatically delete objects no longer in use. after GC determines the object is only weakly reachable JAVA. lang. ref. weakreference
JAVA. util. weakhashmap
Phantom reference Lets you clean up after finalization but before the space is reclaimed (replaces or augments the useFinalize()) Special clean up processing After finalization. Java. Lang. Ref.Phantomreference

8. Summary
General applicationsProgramIt does not involve reference programming, but understanding this knowledge will be helpful for understanding the working principle of GC and Performance Tuning. It may also be used to implement some basic facilities, such as caching, I hope this article will be helpful.

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.