1. System.gc(

  • System.gc or Runtime.getruntime ()
  • System.gc() calls come with a disclaimer that the call to the garbage collector is not guaranteed (there is no guarantee that GC will trigger immediately)
  • For special cases, such as writing performance benchmarks, we can call System.gc between runs,
  • The following code, if marked system.runfinalization (); The console is not guaranteed to print, proving that system.gc () is not guaranteed to execute gc
public class SystemGCTest { public static void main(String[] args) { new SystemGCTest(); System.gc(); // Remind JVM garbage collector to perform GC, but not sure whether to perform GC immediately // with Runtime.getruntime ().gc(); Have the same effect. System.runFinalization(); } @override protected void Finalize () throws Throwable {super.finalize(); System.out.println("SystemGCTest overwrites Finalize ()"); }}Copy the code

Manual GC understands the collection behavior of unreachable objects

public class LocalVarGC { public void localvarGC1() { byte[] buffer = new byte[10 * 1024 * 1024]; //10MB System.gc(); //[GC (system.gc ())] [PSYoungGen: 14174K->10736K(76288K)] 14174K->10788K(251392K), 0.0089741 secs] [Times: User =0.01 sys=0.00, real=0.01 secs] //[Full GC (system.gc ()) [PSYoungGen: 10736K->0K(76288K)] [ParOldGen: [Times: 3253K->3253K], [Metaspace: 3253K->3253K], 0.0074098secs] [Times: 3253K->3253K] User =0.01 sys=0.02, real=0.01 secs]} public void localvarGC2() {byte[] buffer = new byte[10 * 1024 * 1024]; buffer = null; System.gc(); //[GC (system.gc ())] [PSYoungGen: 14174K->544K(76288K)] 14174K->552K(251392K), 0.0011742 secs] [Times: User =0.00 sys=0.00, real=0.00 secs] //[Full GC (system.gc ()) [PSYoungGen: 544K->0K(76288K)] [ParOldGen: 8K->410K(175104K)] 552K->410K(251392K), [Metaspace: 3277K->3277K(1056768K)], 0.0054702 secs] [Times: User =0.01 sys=0.00, real=0.01 secs]} public void localvarGC3() {{byte[] buffer = new byte[10 * 1024 * 1024]; } System.gc(); //[GC (system.gc ())] [PSYoungGen: 14174K->10736K(76288K)] 14174K->10784K(251392K), 0.0076032 secs] [Times: User =0.02 sys=0.00, real=0.01 secs] //[Full GC (system.gc ()) [PSYoungGen: 10736K->0K(76288K)] [ParOldGen: [Times: 3252K->3252K], [Metaspace: 3252K->3252K(1056768K)], 0.0096328secs] [Times: 3252K->3252K(1056768K)] User =0.01 sys=0.01, real=0.01 secs]} public void localvarGC4() {{byte[] buffer = new byte[10 * 1024 * 1024]; } int value = 10; System.gc(); //[GC (system.gc ())] [PSYoungGen: 14174K->496K] 14174K->504K(251392K), 0.0016517 secs] [Times: User =0.01 sys=0.00, real=0.00 secs] //[Full GC (system.gc ()) [PSYoungGen: 496K->0K(76288K)] [ParOldGen: 8K->410K(175104K)] 504K->410K(251392K), [Metaspace: 3279K->3279K(1056768K)], 0.0055183secs] [Times: } public void localvarGC5() {localvarGC1(); System.gc(); //[GC (system.gc ())] [PSYoungGen: 14174K->10720K(76288K)] 14174K->10744K(251392K), 0.0121568secs] [Times: User =0.02 sys=0.00, real=0.02 secs] //[Full GC (system.gc ()) [PSYoungGen: 10720K->0K(76288K)] [ParOldGen: 24K-> 24K (175104K)] 24744K -> 24650k (251392K), [Metaspace: 3279K->3279K(1056768K)], 0.0101068secs] [Times: User =0.01 sys=0.02, real=0.01 secs] //[GC (system.gc ())] [PSYoungGen: 0K->0K [Times: 0K->0K] 1050K -> 1050k [Times: 1050k] 1050k -> 1050k [Times: 1050k] 1050k -> 1050k [Times: 1050k] Sys =0.00, real=0.00 secs] //[Full GC (system.gc ()) [PSYoungGen: 0K->0K(76288K)] [ParOldGen: 10650K->410K(175104K)] 10650K->410K(251392K), [Metaspace: 3279K->3279K(1056768K)], 0.0045963 secs] [Times: Sys =0.00, real=0.00 secs]} public static void main(String[] args) {LocalVarGC local = new LocalVarGC(); local.localvarGC5(); }}Copy the code

2 Memory overflow and memory leak

  • Because GC is constantly evolving, O0M is less likely to occur in general, unless the memory footprint of the application is growing so fast that garbage collection can no longer keep pace with memory consumption
  • In most cases, the GC will do garbage collection for all ages, but if it is too late, it will do an exclusive Full GC operation, which will reclaim a large amount of memory for the application to continue to use
  • The javadoc interpretation of OutOfMemoryError is that there is no free memory, and the garbage collector cannot provide more memory

2.1 Memory Overflow

  • The Heap memory setting of the Java virtual machine is insufficient
  • The code creates a large number of objects that cannot be collected by the garbage collector for a long time (there are references)
  • The implication is that the garbage collector is usually triggered to clean up as much space as it can before an OutOfMemoryError is thrown
  • Of course, the garbage collector is not triggered in every case. For example, if we allocate a large object, such as a large array exceeding the maximum size of the heap, the JVM can determine that garbage collection does not solve the problem, so it simply throws an OutOfMemoryError

2.2 Memory Leak

  • A memory leak is when objects are no longer used by the program, but the GC cannot reclaim them
  • In fact, there are some omissions that cause the object’s life cycle to be very long and even OOM, memory leak in the broad sense
  • A memory leak does not immediately cause a program to crash. However, once a memory leak occurs, the available memory in the program will be gradually eaten up until all memory is exhausted. Finally, an OutOfMemory exception occurs, causing the program to crash

example

  • 1. Singleton mode

The life of a singleton is as long as that of an application, so a singleton that holds a reference to an external object cannot be recycled, resulting in a memory leak

  • 2, some resources that provide close are not closed, resulting in memory leaks, such as database links, network links, and IO

3 Stop The World

  • Stop-the-world, or STW, refers to application pauses that occur during GC events. A pause occurs when the entire application thread is suspended without any response, a bit like being stuck. This pause is called STW
  • Enumerating root nodes (GC Roots) in the reachability analysis algorithm cause all Java execution threads to pause. The analysis must be performed in a snapshot that ensures consistency. Consistency means that the entire execution system appears to be frozen at a point in time throughout the analysis. If the object reference relationship changes during the analysis, the accuracy of the analysis results cannot be guaranteed
  • Application threads that are interrupted by STW will resume after GC, and frequent interruptions will make users feel like a movie tape caused by slow network speed, so we need to reduce STW occurrences
  • The STW event is independent of which GC is used; all GC’s have this event
  • Even the G1 can’t completely avoid stop-the-world situations, except that garbage collectors are getting better and more efficient at collecting, reducing pause times as much as possible
  • STW is automatically initiated and completed by the JVM in the background. When the user is not visible, all the normal working threads of the user are stopped

Code demo

public class StopTheWorldDemo { public static class WorkThread extends Thread { List<byte[]> list = new ArrayList<byte[]>(); public void run() { try { while (true) { for(int i = 0; i < 1000; i++){ byte[] buffer = new byte[1024]; list.add(buffer); } if(list.size() > 10000){ list.clear(); System.gc(); }}} catch (Exception ex) {ex.printStackTrace(); } } } public static class PrintThread extends Thread { public final long startTime = System.currentTimeMillis(); Public void run() {try {while (true) {// Print time information per second long t = system.currentTimemillis () -startTime; System.out.println(t / 1000 + "." + t % 1000); Thread.sleep(1000); } } catch (Exception ex) { ex.printStackTrace(); } } } public static void main(String[] args) { WorkThread w = new WorkThread(); PrintThread p = new PrintThread(); w.start(); p.start(); }}Copy the code

Parallelism and concurrency of garbage collection

  • Concurrency: Several programs running on the same processor at the same time
  • Parallelism: when one CPU executes a process, another CPU can execute another process. The two processes do not seize resources from each other, but can proceed simultaneously. This is called parallelism.
  • The two contrast
    • Concurrency is when multiple things happen at the same time at the same time.
    • Parallelism means multiple things happening at the same time.
    • Concurrent tasks preempt each other’s resources.
    • Parallel tasks do not grab resources from each other.
    • Parallelism occurs only in the case of multiple cpus or one CPU with multiple cores. Otherwise, everything that seems to happen at the same time is actually executed concurrently

5 Security points and zones

5.1 Safepoint

  • Program execution does not stop everywhere to begin GC, but only at certain points, called safe points
  • The choice of Safe Points is important because too little can lead to long GC waits, and too often can cause performance problems at runtime. The execution time of most instructions is very short, and is usually based on “characteristics that make the program run for a long time”. For example, select instructions that take longer to execute as Safe points, such as method calls, loop jumps, and exception jumps

How do you check that all threads stop at the nearest safe point when a GC occurs?

  • Preemptive interrupt: (no virtual machine currently uses it) interrupts all threads first. If there are still threads that are not at the safe point, restore the thread and let it run to the safe point
  • Active Interrupts: Sets an interrupt flag, which threads actively poll when running to Safe Point, and suspends themselves if the interrupt flag is true

5.2 Safe Region

  • The Safepoint mechanism ensures that when a program executes, it will not take too long to encounter a Safepoint ready for GC. But what about when the program “doesn’t execute”? For example, when a thread is in the state of Sleep or Blocked, unable to respond to interrupt requests from the JVM, the thread “walks” to a safe point to interrupt the suspension, and the JVM is less likely to wait for the thread to wake up. In this case, a Safe Region is required
  • A safe zone is a code snippet where the reference relationship of the object does not change and it is safe to start GC anywhere in the zone. We can also think of Safe Region as Safepoint extended

Execution time:

  • 1. When a thread runs into Safe Region code, it first identifies that it has entered the Safe Region. If GC occurs during that time, the JVM ignores the thread identified as Safe Region.
  • When a thread is about to leave the SafeRegion, it checks to see if the JVM has completed GC, and if so, continues running. Otherwise, the thread must wait until it receives a signal that it is Safe to leave SafeRegion.

6,

  • When the memory space is sufficient, it can be retained in the memory. If memory space is tight after garbage collection, these objects can be discarded. What is the difference between strong citation, soft citation, weak citation and virtual citation? What are the scenarios?
  • Since JDK 1.2, Java has expanded the concept of references to include Strong references

Reference, Soft Reference, Weak Reference and Phantom Reference. The intensity of these four references gradually decreases

  • Except for strong references, the other three references can be found in the java.lang.ref package. The figure below shows the classes that correspond to these three reference types, and developers can use them directly in their applications

In the Reference subclass, only finalizer references are visible within the package. The other three Reference types are public and can be used directly in applications

  • StrongReference I: A traditional definition of “reference” refers to a reference assignment common in program code, such as Object obj= New Object (). In any case, the garbage collector will never reclaim the referenced object as long as the strong reference relationship exists
  • Soft references: Objects are collected for a second collection before the system is about to run out of memory. An out-of-memory exception is thrown if there is not enough memory after this collection
  • WeakReference: an object associated with a WeakReference can only survive until the next garbage collection. When the garbage collector works, objects associated with weak references are reclaimed regardless of whether there is enough memory
  • PhantomReference: Whether an object has a virtual reference that does not exist for it at all

There is no way to obtain an instance of an object through a virtual reference. The only purpose of setting a virtual reference association for an object is to receive a system notification when the object is reclaimed by the collector (reclaim trace)

6.1 Strong Reference: No reclamation

  • In Java programs, the most common type of reference is strong reference (more than 99% of all strong references in normal systems), which is our most common plain object reference and the default reference type.
  • When you use the new operator in the Java language to create a new object and assign it to a variable, the variable becomes a strong reference to the object.
  • Strongly referenced objects are touchable, and the garbage collector will never reclaim the referenced objects
  • Strong references are one of the main causes of Java memory leaks

Code demo

public class StrongReferenceTest { public static void main(String[] args) { StringBuffer str = new StringBuffer ("Hello, Silicon Valley "); StringBuffer str1 = str; str = null; System.gc(); try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(str1); }}Copy the code

StringBuffer STR = new StringBuffer (“Hello “); The local variable STR refers to the heap where the StringBuffer instance resides, and STR is used to manipulate the instance, so STR is a strong reference to the memory structure of the StringBuffer instance:At this point, if you run an assignment statement: StringBuffer str1 = STR; Corresponding memory structure:Both references in this example are strong references, which have the following characteristics:

  • Strong references allow direct access to the target object.
  • The object pointed to by a strong reference will not be reclaimed by the system at any time. The VM would rather throw an OOM exception than reclaim the object pointed to by a strong reference.
  • Strong references can lead to memory leaks

6.2 Soft Reference: If the memory is insufficient, it is reclaimed

  • Before the system runs out of memory, the objects are included in the collection range for a second collection. If there is not enough memory after the collection, an out of memory exception is thrown
  • Soft references are often used to implement memory sensitive caching. For example, caching is useful for soft references. If you have free memory, you can keep the cache for a while and clean it up when you run out of memory. This ensures that you don’t run out of memory while using the cache
  • When the garbage collector decides to reclaim soft reachable objects at some point, it cleans up soft references and optionally stores them in a Reference Queue.
  • Soft references:
    • When memory enough: not recycling soft | use of objects
    • When memory runs out: Reachable soft-referenced objects are reclaimed
  • In JDK 1. 2 after edition provides a Java. Lang. Ref. SoftReference class to achieve soft references

Code demo

/** * Test for soft references: -xms10m -XMx10m -xx :+PrintGCDetails */ public class SoftReferenceTest {public static class User {public User(int id, String name) { this.id = id; this.name = name; } public int id; public String name; @Override public String toString() { return "[id=" + id + ", name=" + name + "] "; }} public static void main(String[] args) { Setting up a SoftReference // SoftReference<User> userSoftRef = new SoftReference<User>(new User(1, "songhk")); // This is equivalent to the following three lines User u1 = new User(1,"songhk"); SoftReference<User> userSoftRef = new SoftReference<User>(u1); u1 = null; // Remove strong references // Retrieve strong references from soft references system.out.println (usersoftref.get ()); System.gc(); System.out.println("After GC:"); // // gets the object in the soft reference system.out.println (usersoftref.get ()) after garbage collection; // Reachable objects that do not recycle soft references due to sufficient heap space memory. Byte [] b = new byte[1024 * 1024 * 7]; byte[] b = new byte[1024 * 1024 * 7]; byte[] b = new byte[1024 * 7168 - 399 * 1024]; } catch (e) {e.printstackTrace (); System.out.println(usersoftref.get ())); system.out.println (usersoftref.get ()); // The garbage collector will reclaim soft-referenced reachable objects before reporting OOM. }}}Copy the code

6.3 Weak Reference: Discovery is reclaiming

  • Objects associated with weak references only survive until the next garbage collector, when the garbage collector works and reclaims objects associated with weak references regardless of whether there is enough memory
  • However, because garbage collector threads are usually of low priority, objects holding weak references are not always found quickly. In this case, weak reference objects can exist for a long time
  • Both soft and weak references are great for storing cache data that is not essential. If you do this, when the system runs out of memory, the cached data will be reclaimed without running out of memory. When memory resources are sufficient, these cached data can exist for quite a long time, thus speeding up the system
  • The big difference between a weak-referenced object and a soft-referenced object is that when the GC is collecting, the algorithm checks to see if the soft-referenced object is being collected, whereas for weak-referenced objects, the GC always collects. Weakly referenced objects are easier and faster to collect by GC
  • After JDK1.2 version of a Java 2 Tim. Lang. Ref. The WeakReference class to implement a weak reference
  • Interview question: Have you used WeakHashMap in your development? By looking at WeakHashMap source code, you can see that its internal class Entry uses weak references. line 702 private static class Entry<K,V> extends WeakReference implements Map.Entry<K,V>

    Code demo

    public class WeakReferenceTest { public static class User { public User(int id, String name) { this.id = id; this.name = name; } public int id; public String name; @Override public String toString() { return "[id=" + id + ", name=" + name + "] "; WeakReference<User> userWeakRef = new WeakReference<User>(new) WeakReference<User>(new) User(1, "songhk")); // Retrieve the object system.out.println (userWeakref.get ()); System.gc(); System.out.println("After GC:"); system.out.println ("After GC:"); // Try again to get the object system.out.println (userWeakref.get ()) from the weak reference; }}Copy the code

    6.4 Virtual Reference: Object reclamation trace

    • The existence of virtual references to an object does not determine its life cycle at all. If an object holds only virtual references, it is almost as good as no references and can be collected by the garbage collector at any time

    • The sole purpose of setting a virtual reference association for an object is to track the garbage collection process. For example, you can receive a system notification when the object is reclaimed by the collector

    • The PhantomReference class was provided after JDK 1. 2 to implement virtual references

    Play this demo

    public class PhantomReferenceTest { public static PhantomReferenceTest obj; Static ReferenceQueue<PhantomReferenceTest> phantomQueue = null; Public static class CheckRefQueue extends Thread {@override public void run() {while (true) {if (phantomQueue) ! = null) { PhantomReference<PhantomReferenceTest> objt = null; try { objt = (PhantomReference<PhantomReferenceTest>) phantomQueue.remove(); } catch (InterruptedException e) { e.printStackTrace(); } if (objt ! = null) {system.out.println (" Trace garbage collection: PhantomReferenceTest instance was GC "); }}}}} @override protected void finalize() throws Throwable {// Finalize () method can only be called once! super.finalize(); System.out.println(" Call the finalize() method of the current class "); obj = this; } public static void main(String[] args) { Thread t = new CheckRefQueue(); t.setDaemon(true); Daemons are terminated when there are no non-daemons in the program. t.start(); phantomQueue = new ReferenceQueue<PhantomReferenceTest>(); obj = new PhantomReferenceTest(); // Create a virtual reference to the PhantomReferenceTest object PhantomReference<PhantomReferenceTest> phantomRef = new PhantomReference<PhantomReferenceTest> phantomQueue); System.out.println(phantomref.get ())); // remove strong references obj = null; System.gc(); system.gc (); system.gc (); Thread.sleep(1000); If (obj == null) {system.out.println ("obj is null"); } else {system.out.println ("obj available "); } system.out. println(" 2nd gc"); obj = null; System.gc(); // Once the obj object is reclaimed, the virtual reference is placed in the reference queue. Thread.sleep(1000); If (obj == null) {system.out.println ("obj is null"); } else {system.out.println ("obj available "); } } catch (InterruptedException e) { e.printStackTrace(); }}}Copy the code

    The output

    Null calls the finalize() method obj of the current class for the second gc to track the garbage collection process: PhantomReferenceTest instance was gc and obj is nullCopy the code

    6.5 Finalizer References

    • It is used to implement an object’s Finalize () method, which can also be called a finalizer reference.
    • No manual encoding is required, and it is used internally with reference queues.
    • During GC, finalizer references are enqueued. When the Finali zer thread finds the referenced object through the finalizer reference and calls its Finalize () method, the referenced object can be reclaimed on the second GC.

    JVM full directory

    Class loading mechanism 3. Runtime data area [PC register, vm stack, local method stack] 4. Runtime data area [heap] 5. Runtime data area [method area] 6. Temporary absence 7. Runtime data area [instantiated memory layout and access location of objects, direct memory] 8. String constant pool 10. Garbage collection [overview, related algorithms] 11. Garbage collection [related concepts] 12. Common OOM 14. JDK command line tools