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];
            }
        }
    }

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

  • 相关阅读:
    004---基于TCP的套接字
    003---socket介绍
    002---tcp/ip五层详解
    001---C/S架构
    008---re正则模块
    007---logging日志模块
    006---hashlib模块
    005---json & pickle
    004---os & sys
    22.解决 eclipse 与 AS 共用 SDK 导致 eclipse ADT 无法使用的问题
  • 原文地址:https://www.cnblogs.com/coolgame/p/8797658.html
Copyright © 2011-2022 走看看