GC and ghost references in Java are fully resolved

  • 2020-04-01 02:15:11
  • OfStack

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 usage scenarios one by one:

1, Strong Reference
StrongReference is the default reference implementation of Java,& sponge; It will live in the JVM as long as possible, and when no objects point to it, the GC will be recovered

Java code


@Test  
public void strongReference() {  
    Object referent = new Object();  

      
    Object strongReference = referent;  

    assertSame(referent, strongReference);  

    referent = null;  
    System.gc();  

      
    assertNotNull(strongReference);  
}  

2. WeakReference & WeakHashMap
WeakReference, as the name implies,  Is a weak reference,  Weak reference will be collected automatically after GC when the referenced object no longer has a strong reference in the JVM

@Test  
public void weakReference() {  
    Object referent = new Object();  
    WeakReference<Object> weakRerference = new WeakReference<Object>(referent);  

    assertSame(referent, weakRerference.get());  

    referent = null;  
    System.gc();  

      
    assertNull(weakRerference.get());  
}  

WeakHashMap USES WeakReference as the key. Once there is no strong reference to the key, WeakHashMap will automatically delete the relevant entry after GC

@Test  
public void weakHashMap() throws InterruptedException {  
    Map<Object, Object> weakHashMap = new WeakHashMap<Object, Object>();  
    Object key = new Object();  
    Object value = new Object();  
    weakHashMap.put(key, value);  

    assertTrue(weakHashMap.containsValue(value));  

    key = null;  
    System.gc();  

      
    Thread.sleep(1000);  

      
    assertFalse(weakHashMap.containsValue(value));  
}  

3, SoftReference
SoftReference is basically the same as WeakReference, the big difference being that it retains the reference as long as possible until the JVM runs out of memory (virtual machine guarantees), which makes it ideal for caching applications

@Test  
public void softReference() {  
    Object referent = new Object();  
    SoftReference<Object> softRerference = new SoftReference<Object>(referent);  

    assertNotNull(softRerference.get());  

    referent = null;  
    System.gc();  

      
    assertNotNull(softRerference.get());  
}  

4, PhantomReference
As the protagonist of this article, a Phantom Reference is quite different from a WeakReference and a SoftReference,& slack; Because its get() method always returns null, that's where its name comes from

Java code


@Test  
public void phantomReferenceAlwaysNull() {  
    Object referent = new Object();  
    PhantomReference<Object> phantomReference = new PhantomReference<Object>(referent, new ReferenceQueue<Object>());  

      
    assertNull(phantomReference.get());  
}  

You might ask what is the use of a reference that always returns null,& PI; Notice that the second parameter, ReferenceQueue, when PhantomReference is constructed (in fact, WeakReference & softrereference can also have this parameter),
PhantomReference's only use is to trace the referent& PI; When it is enqueued to the ReferenceQueue.

5, RererenceQueue
When a WeakReference starts to return null, the object it points to is ready to be recycled, and some proper cleanup can be done.   Pass a ReferenceQueue to a Reference constructor, and when the object is retrieved, the vm will automatically insert the object into the ReferenceQueue. WeakHashMap USES the ReferenceQueue to clear entries that have no strong references to the key.

Java code


@Test  
public void referenceQueue() throws InterruptedException {  
    Object referent = new Object();       
    ReferenceQueue<Object> referenceQueue = new ReferenceQueue<Object>();  
    WeakReference<Object> weakReference = new WeakReference<Object>(referent, referenceQueue);  

    assertFalse(weakReference.isEnqueued());  
    Reference<? extends Object> polled = referenceQueue.poll();  
    assertNull(polled);  

    referent = null;  
    System.gc();  

    assertTrue(weakReference.isEnqueued());  
    Reference<? extends Object> removed = referenceQueue.remove();  
    assertNotNull(removed);  
}  

6, PhantomReference  Vs WeakReference
PhantomReference  There are two benefits. First, it allows us to know exactly when objects are deleted from memory, a feature that can be used for specific requirements (e.g. PhantomReference is also used in XWork and google-guice to do some cleaning work).

Secondly, it can avoid some fundamental problems caused by finalization. As mentioned above, PhantomReference's only function is to track when the referent is enqueued to the ReferenceQueue,& PI; However, WeakReference also has corresponding functions. Where is the difference between the two?

This brings us to the Object finalize method, which is called before the gc is executed, if an Object overloads the finalize method and intentionally creates a strong reference to itself within the method,  This will result in this round of GC can't recycle this object and is likely to cause any number of times the GC, but the final result is that the JVM obviously has a lot of Garbage OutOfMemory, use PhantomReference can avoid this problem, because the PhantomReference is recycled after finalize method was implemented, which means at this time was not possible to get the original reference, also won't appear afore-mentioned problems,   Of course, this is an extreme example that doesn't usually occur.

7, contrast
Soft vs Weak vs Phantom References The Type The Purpose Use The 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. The 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 decided that it still needed to reclaim more space. Java. Lang. Ref. SoftReference Weak Reference Keeps objects alive only while they 'r e 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 the or augments the use offinalize ()) Special clean up processing After finalization. Java. Lang. Ref. PhantomReference

 

 

Nodule 8.
Reference programming is not normally involved in an application, but knowing this will help you to understand how GC works and how to tune performance, as well as to implement infrastructure such as caching, which I hope will be helpful in this article.


Related articles: