zoukankan      html  css  js  c++  java
  • 关于JAVA垃圾回收的一些小tips

    public class AliveTest {
        public static AliveTest A = null;
        public static void alive(){
            System.out.println("alive");
        }
        protected void finalize() throws Throwable {
            super.finalize();
            System.out.println("finalize");
            AliveTest.A = this;
            //System.out.println(A);
        }
        public static void main(String[] args) throws InterruptedException {
            A = new AliveTest();
            A=null;
            System.gc();
            Thread.sleep(500);
            if(A!=null){
                AliveTest.alive();
            }else{
                System.out.println("hehe");
            }
            
            A=null;
            System.gc();
            Thread.sleep(500);
            if(A!=null){
                AliveTest.alive();
            }else{
                System.out.println("aa");
            }
        }
    }

    Java 虚拟机在垃圾回收的时候最多只调用一次 finalize 方法;

    public class ReferenceTest {
        public static final Map<Integer, Reference> map = new HashMap<Integer, Reference>();
        
        public static void main(String[] args) {
            for (int i = 0; i < 1000; i++) {
                map.put(i, new WeakReference(new ReferenceObject(i)));
            }
     
            int i = 0;
            for (Reference r : map.values()) {
                if (r.get() == null) {
                    i++;
                }
            }
            System.out.println("被回收的对象数:" + i);
        }
     
        static class ReferenceObject {
            private int    i;
     
            private byte[] b;
     
            public ReferenceObject(int i) {
                this.i = i;
                b = new byte[1024 *10000];
            }
        }
    }

    弱引用马上就会被回收掉。

  • 相关阅读:
    jvm字节码简介
    Class类文件结构
    springboot 配置webservice接口
    jdk(1.8)命令行工具(二)
    springboot集成JsonRpc2.0
    jdk命令行工具(一)
    linux安装spark-2.3.0集群
    linux安装scala环境
    [机器学习实践] 针对Breast-Cancer数据集
    mac下 selenium + python 配置和入门
  • 原文地址:https://www.cnblogs.com/coolgame/p/8797658.html
Copyright © 2011-2022 走看看