The article directories

    • The JAVA virtual machine
      • Shared data area
        • Methods area
        • The Java heap
      • Thread private
        • Program counter PC
        • The virtual machine stack
        • Local method stack
    • GC garbage collector
      • Reference counting algorithm
      • Accessibility analysis algorithm
      • The relationship between reclaim and reference types
        • Strong reference StrongReference
        • Soft references (SoftReference)
        • A weak reference (WeakReference)
        • Phantom reference (PhantomReference)

The JAVA virtual machine



Shared data area

Methods area

  • ClassLoader loads the compiled code for class information constants, static variables
  • OOM
  • Runtime constant pool literals public satic final Java constants, symbolic reference classes, full interface names, and method names

The Java heap

  • The largest chunk of memory managed by virtual machines is the main battleground for GC
  • OOM
  • The contents of an array of object instances

Thread private

Program counter PC

  • An indicator that identifies the address of the next line of code to be executed
  • Each thread has one
  • There is no OOM section

The virtual machine stack

  • This is what we call the stack
  • Outofmemory and StackOverflow exceptions are defined in the Java Virtual Machine specification

Local method stack

  • Outofmemory and StackOverflow exceptions are defined in the Java Virtual Machine specification
  • HotspotVM combines the virtual machine stack and the local method stack into one stack area

GC garbage collector

Reference counting algorithm

Object o1=new Object(); +1=1 Object O2; o2=o1; Count + 1 = 2 o1 = null; Count one, o1 and O2 are not recycledCopy the code
  • Cons: Cross-references tend to occur when calculators are never 0

Accessibility analysis algorithm

  • Can be an object for GC ROOT
  • The reference used by the virtual machine stack is running
  • Static attribute constant
  • Objects referenced by JNI
  • GC takes two scans to collect objects, so we can use Finalize to save objects that are lost
static App a;
@Override
protected void() throws Throwable{
	super.finalize();
	a=this;
}
Copy the code

The relationship between reclaim and reference types

  • Level and strength: Strong reference -> Soft reference -> Weak reference -> Virtual reference

Strong reference StrongReference

Object strongReference = new Object();
Copy the code
  • When running out of memory, the Java virtual machine would rather throw OutofMemoryErrors to abort the program than randomly recycle objects with strong references.
  • If a strongly referenced object is not in use, you need to weaken it so that the GC can reclaim it. StrongReference = NULL.
  • If you explicitly set the strongReference object to NULL, the GC considers that the object can be reclaimed. The collection time depends on the GC algorithm
  • If the strongReference is a global variable, you need to assign null if the object is not used, because strong references are not garbage collected
  • The source code for ArrayList includes this passage:
 public void clear() {
            modCount++;

            // clear to let GC do its work
            for (int i = 0; i < size; i++)
                elementData[i] = null;

            size = 0;
        }
Copy the code

The arrayList class defines an array of elementData, and each element of the array is assigned null when the clear method is called to empty the array. Unlike elementData=null, strong references still exist, avoiding memory reallocation in subsequent calls to methods such as add() to add elements. It is particularly useful to free memory using reference types stored in the memory array of the clear() method so that memory can be freed in time.

Soft references (SoftReference)

  • If an object has only soft references, the garbage collector will not reclaim it when there is enough memory; If you run out of memory, the objects are reclaimed. As long as the garbage collector does not collect it, the object can be used by the program.
  • Soft references can be used to implement memory sensitive caching.
  • It’s only reclaimed when it’s out of memory,
  • When a JVM scans for a reclaimed object is determined by the JVM’s own state, and it does not necessarily reclaim a soft reference object when it is scanned, but only when there is insufficient memory.
 String str = new String("abc");
    SoftReference<String> softReference = new SoftReference<String>(str);
Copy the code
  • A soft reference is used in conjunction with a ReferenceQueue (ReferenceQueue), and if the object referenced by the soft reference is garbage collected, the JAVA virtual machine adds the soft reference to the ReferenceQueue associated with it
ReferenceQueue<String> referenceQueue = new ReferenceQueue<>(); String str = new String("abc"); SoftReference<String> softReference = new SoftReference<>(str, referenceQueue); str = null; System.gc(); // Notify GC only notifies the GC to collect, depending on the state of memory and JVM. System.out.println(softReference.get()); // abc Reference<? extends String> reference = referenceQueue.poll(); System.out.println(reference); //nullCopy the code
  • When out of memory, the JVM first sets the object reference in the soft reference to NULL, and then notifies the garbage collector for collection
If (JVM out of memory) {// Set the object reference in the soft reference to null STR = null; // Tell the garbage collector to collect system.gc (); }Copy the code
  • The garbage collection thread will reclaim soft reference objects before the VIRTUAL machine throws OutOfMemoryError, and the virtual machine will reclaim soft reference objects that have been idle for a long time first if possible. Newer soft objects that have just been built or used are retained by the virtual machine as much as possible, which is why ReferenceQueue was introduced for the ReferenceQueue.
  • Application: The browser’s back button. When you press Back, the page content displayed when the back is rerequested or retrieved from the cache
// Get Browser object to browse Browser Browser = new Browser(); BrowserPage = browser.getPage(); // set the page to a SoftReference SoftReference SoftReference = new SoftReference(page). // If (softreference.get ()! Page = softreference.get (); page = softReference. } else {// Out of memory, soft-referenced object already recycled page = browser.getPage(); // rebuild the softReference softReference = new softReference (page); }Copy the code

A weak reference (WeakReference)

  • Objects with weak references have a shorter lifetime than soft references. When the garbage collector thread scans the memory area under its control, once it finds an object with only weak references, it reclaims its memory regardless of whether the current memory space is sufficient. However, because the garbage collector is a low-priority thread, objects that have only weak references are not necessarily found quickly.
  • The JVM first sets the object reference in the soft reference to NULL and then notifies the garbage collector for collection
@Test public void testWeakReference() throws InterruptedException { ReferenceQueue<Object> referenceQueue = new ReferenceQueue<>(); Object weakObject = new Object(); / / weak references Add objects to the queue gc sweep into the first time, and mark, the second sweep to direct recycling WeakReference WeakReference = new WeakReference (weakObject referenceQueue); System.out.println("WeakReference:"+ WeakReference.get ()); System.out.println("referenceQueuee:"+referenceQueue.poll()); weakObject =null; System.gc(); Thread.sleep(2000); System.out.println("WeakReference:"+weakReference.get()); System.out.println("referenceQueuee:"+referenceQueue.poll()); / / results gc before recycling can get to the object But the poll () is null / / WeakReference: Java lang. Object @ 2957 fcb0 / / referenceQueuee: null / / gc after get less than the Object, But you can poll the information that the object created in memory, When the get less than the object that the object has been recycling/gc/WeakReference: null / / referenceQueuee: Java. Lang. Ref. WeakReference @ 1376 c05c}Copy the code
  • If an object is used sporadically (infrequently) and you want it to be available whenever you use it, but you don’t want to affect the garbage collection of the object, then you should use Weak Reference to remember the object.

Phantom reference (PhantomReference)

  • Virtual references do not determine the life cycle of the object. If an object holds only virtual references, it can be collected by the garbage collector at any time, just as if there were no references at all
  • Mainly used to track the activity of objects being collected by the garbage collector
  • Virtual references are distinguished from soft and weak references
  • A virtual reference must be used in conjunction with a ReferenceQueue. When the garbage collector is about to reclaim an object and finds that it has a virtual reference, it adds the virtual reference to the reference queue associated with it before reclaiming the object’s memory.
@test public void testPhantomReference() throws InterruptedException {// Virtual reference: It does not affect the life cycle of the object, but it does let the programmer know when the object has been reclaimed. ReferenceQueue > ReferenceQueue = new ReferenceQueue<>(); Object phantomObject = new Object(); PhantomReference phantomReference = new PhantomReference(phantomObject,referenceQueue); phantomObject = null; System.out.println("phantomObject:"+phantomObject); //null System.out.println("phantomReference"+referenceQueue.poll()); //null System.gc(); Thread.sleep(2000); System.out.println("referenceQueuee:"+referenceQueue.poll()); / / the result: PhantomObject :null // phantomReferencenull :null // phantomReferencenull :null Can judge object at this time has been recycling / / referenceQueuee: Java. Lang. Ref. PhantomReference @ 2957 fcb0}Copy the code
Reference types Time to be garbage collected use Time to live
Strong reference never The general state of the object Terminates when the JVM stops running
Soft references When memory is low Object caching Terminates when out of memory
A weak reference Normal garbage collection Object caching Garbage after recycling
Phantom reference Normal garbage collection Track the garbage collection of objects Garbage collection terminates