JAVA's four kinds of strong, weak, and weak references

A variable points to a new object, which is a reference. There are four kinds of references in Java, which are strong and weak. The common Object o = new Object () is a strong reference. When garbage collection, strong references will not be recycled.

  •     Common class:
    public class M {
        @Override
        protected void finalize() throws Throwable {
            System.out.println("finalize");
        }
    }
  • Strong: As long as there is a reference, the code will not be recycled:
    public  class T01_NormalReference {
         public  static  void main (String [] args) throws IOException { 
            M m = new M (); 
            m = null ; // Only when there is no reference, the object m of M will be recycled 
            System.gc (); // DisableExplicitGC 
            System.in.read (); // The purpose of blocking the thread is: because GC is running in other threads, it is likely that the thread has ended before it is started without blocking. 
        } 
    }

     

  • Soft: Reclaim space is not enough, used to cache
    code: first set VM options: -Xms20M -Xmx20M (set the maximum and minimum heap memory are 20M)
    public class T02_SoftReference {
        public static void main(String[] args) {
            SoftReference<byte[]> m = new SoftReference<>(new byte[1024*1024*10]);
            //m = null;
            System.out.println(m.get());
            System.gc();
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(m.get());
            //If you allocate another array, the heap will not fit. At this time, the system will be garbage collected. First, it will be collected once. If it is not enough, the soft reference will be killed. At this time, the printed result should be empty 
            byte [] b = new  byte [1024 * 1024 * 15 ]; 
            System.out.println (m.get ()); 
        } 
    }

     

  • Weak reference : As long as the garbage collection (System.gc ()) is called, it is recycled. Application scenario: As long as the strong reference disappears, it should be recycled. It is generally used in containers. The typical application is ThreadLock. See WeakHashMap, AQSunlock source code (Tomcat cache Used weak application)
    code:
    public  class T03_WeakReference {
         public  static  void main (String [] args) { 
            WeakReference <M> m = new WeakReference <> ( new M ()); 
            System.out.println (m.get ()); 
            System.gc () ; 
            System.out.println (m.get ()); 
            ThreadLocal <M> tl = new ThreadLocal <> (); 
            tl.set ( new M ()); 
            tl.remove (); // Must use ThreadLocal remove, otherwise there is still a memory leak 
        } 
    }
  • Weak reference example subroutine
    public class ThreadLocal2 {
        static ThreadLocal<Person> tl = new ThreadLocal<>();
        public static void main(String[] args) {
    
            new Thread(()->{
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                tl.set(new Person());
            }).start();
        }
        static class Person {
            String name = "zhangsan";
        }
    }

    Example illustration:



     

  • Virtual reference, mainly used for external memory. Generally used by people who engage in JVM, so basically useless .
    1. Off-heap memory.
         There is a Buffer in NIO, called DirectByteBuffer (direct memory, not managed by jvm virtual machine), also called off-heap memory, managed by the operating system. If this reference is set to a null value, it cannot be recovered. When using a virtual reference
         , Check Queue, and clean up off-heap memory if it is recycled. Java uses freeMemory in Unsave to recycle the off-heap memory.
    2. It will be associated with a queue. When the virtual reference is recycled, it will be received into the associated queue. That is to give you a notification that it has been recycled. The value in the weak reference is You can get it. The virtual reference is less than
    3. The garbage collector comes over and it is directly recovered.
  • Verification procedure (first set the heap memory to 20M, VM options: -Xms20M -Xmx20M, the maximum and minimum heap space in the production environment are set to the same)
    public class T04_PhantomReference {
        private static final List<Object> LIST = new LinkedList<>();
        private static final ReferenceQueue<M> QUEUE = new ReferenceQueue<>();
        public static void main(String[] args) {
            PhantomReference<M> phantomReference = new PhantomReference<>(new M(), QUEUE);
            new Thread(() -> {
                while (true) {
                    LIST.add(new byte[1024 * 1024]);
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                        Thread.currentThread().interrupt();
                    }
                    System.out.println(phantomReference.get());
                }
            }).start();
            new Thread(() -> {
                while (true) {
                    Reference<? extends M> poll = QUEUE.poll();
                    if(poll! = null ) { 
                        System.out.println ( "--- The virtual reference object was recovered by jvm ----" + poll); 
                    } 
                } 
            }). start (); 
            try { 
                Thread.sleep ( 500 ) ; 
            } catch (InterruptedException e) { 
                e.printStackTrace (); 
            } 
        } 
    }

     

Guess you like

Origin www.cnblogs.com/Courage129/p/12734506.html