• Java 清理和垃圾回收


    java.lang.ref.cleaner包

    finalize()//该方法已过时,有风险,慎用

    1.对象不可能被垃圾回收

    2.垃圾回收并不等于"析构"

    只有当垃圾回收发生时finalize()才得到调用,否则对象就会一直保存下来,知道程序结束,将资源交还系统

    3.垃圾回收只与内存又关,垃圾回收和终结都不保证会一定发生  //可以使用system.gc() 提醒 虚拟机回收

    System.runFinalization(); //强制调用已经失去引用的对象的finalize方法 

    可以使对象引用指向null强制对象失去引用

    //: object/TerminationCondition.java
    /**@version 1.0
     * @author  fei long
     */
    package object;
    
    class Book {
        boolean checkedOut = false;
        Book(boolean checkOut)
        {
            checkedOut = checkOut;
        }
        void checkIn()
        {
            checkedOut =false;
        }
        protected void finalize()
        {
            if(checkedOut)
            {
                System.out.println("Error: checked out");
            }
        }
    }
    public class TerminationCondition{
        public static void main(String[] args)
        {
            Book novel = new Book(true);
            novel.checkIn();
            new Book(true);
            System.gc();   //提醒虚拟机回收
    System.runFinalization();//强制调用已经失去引用的对象的finalize方法  } }
    /* output Error: checked out *///~

     继承和清理: 通过组合和继承方法来创建新类时,永远不必担心对象的清理为你,子类通常留给垃圾回收器进行处理,如果遇到清理的问题,那么必须为新类创建dispose()方法,并且由于继承的缘故,如果我们有其它作为垃圾回收一部分的特殊清理动作,就必须在导出类中覆盖dispose方法,当覆盖被继承类的dispose()方法时,务必调用基类版本的dispose()方法,否则基类的清理动作就不会发生,

    //: polymorphism/Forg.java
    // cleanup an inheritance
    package object;
    
    import static net.mindview.util.Print.*;
    
    class Characteristic{
        private String s;
        Characteristic(String s)
        {
            this.s = s;
            print("Creating Characteristic " + s);
        }
        protected void dispose()
        {
            print("disposing characteristic " + s);
        }
    }
    class Description{
        private String s;
        Description(String s)
        {
            this.s = s;
            print("Creating Description " + s);
        }
        protected void dispose()
        {
            print("disposing description" + s);
        }
    }
    class LivingCreature{
        private Characteristic p =
                new Characteristic("is alive");
        private Description t =
                new Description("Basic living creature");
        LivingCreature()
        {
            print("livingcreature");
        }
        protected void dispose()
        {
            print("livingCreature dispose");
            t.dispose();
            p.dispose();
        }
    }
    class Animal extends LivingCreature{
        private Characteristic p = 
                new Characteristic("has heart");
        private Description t = 
                new Description("animal not vegetalbe");
        Animal(){print("Animal()");}
        protected void dispose()
        {
            print("Animal dispose");
            t.dispose();
            p.dispose();
            super.dispose();
        }
    }
    class Amphibian extends Animal
    {
        private Characteristic p =
                new Characteristic("can live in water");
        private Description t =
                new Description("Both water an land");
        Amphibian()
        {
            print("Amphibian()");
        }
        protected void dispose()
        {
            print("Amphibian dispose");
            t.dispose();
            p.dispose();
            super.dispose();
        }
    }
    public class Frog extends Amphibian{
        private Characteristic p = new Characteristic("Croaks");
        private Description t = new Description("Eats bugs");
        public Frog()
        {
            print("Forg()");
            t.dispose();
            p.dispose();
            super.dispose();
        }
        public static void main(String[] args)
        {
            Frog frog = new Frog();
            print("bye!");
            frog.dispose();
        }
    }/* output: 消费的顺序和初始化的顺序相反
    Creating Characteristic is alive
    Creating Description Basic living creature
    livingcreature
    Creating Characteristic has heart
    Creating Description animal not vegetalbe
    Animal()
    Creating Characteristic can live in water
    Creating Description Both water an land
    Amphibian()
    Creating Characteristic Croaks
    Creating Description Eats bugs
    Forg()
    disposing descriptionEats bugs
    disposing characteristic Croaks
    Amphibian dispose
    disposing descriptionBoth water an land
    disposing characteristic can live in water
    Animal dispose
    disposing descriptionanimal not vegetalbe
    disposing characteristic has heart
    livingCreature dispose
    disposing descriptionBasic living creature
    disposing characteristic is alive
    bye!
    Amphibian dispose
    disposing descriptionBoth water an land
    disposing characteristic can live in water
    Animal dispose
    disposing descriptionanimal not vegetalbe
    disposing characteristic has heart
    livingCreature dispose
    disposing descriptionBasic living creature
    disposing characteristic is alive
    *///~

     三,当一个成员对象存在于其它一个或多个对象共享的情况时,也许就必须使用引用计数来跟踪仍旧访问着共享对象的对象数量了.

    //: polymorphism/ReferenceCounting.java
    //  Cleaning up shared member objects
    package object;
    import static net.mindview.util.Print.*;
    
    class Shared{
        private int refcount =0;
        private static long counter  = 0; //记录该类总共的对象个数
        private final long id = counter++; //final 表示不希望再对象生命周期内ID的值被改变
        public Shared()
        {
            print("Creating " + this);
        }
        public void addRef(){refcount++;} //记录同一个对象被引用的次数
        public void dispose()
        {
            if(--refcount == 0)  //当被引用数只有一个时执行清理
                print("Disposing " + this);
        }
        public String toString(){return "Share " + id;}
    }
    class Composting{
        private Shared shared;
        private static long counter = 0;
        private final long id = counter++;
        public Composting(Shared shared)
        {
            print("Creating " + this);
            this.shared= shared;
            this.shared .addRef();
        }
        protected void dispose()
        {
            print("disposing " + this);
            shared.dispose();
        }
        public String toString(){return "Composing " + id;} 
    }
    public class ReferenceCounting{
        public static void main(String[] args)
        {
            Shared shared = new Shared();
            Composting[] composting = { new Composting(shared),
                    new Composting(shared),new Composting(shared),
                    new Composting(shared),new Composting(shared),
                };
            for(Composting c : composting)
                c.dispose();
        }
    }/* output:
    Creating Share 0
    Creating Composing 0
    Creating Composing 1
    Creating Composing 2
    Creating Composing 3
    Creating Composing 4
    disposing Composing 0
    disposing Composing 1
    disposing Composing 2
    disposing Composing 3
    disposing Composing 4
    Disposing Share 0
    *///:~
  • 相关阅读:
    Callable的Future模式
    并发队列
    并发工具类
    线程池
    并发编程专题
    侧边栏:内有友链,分类等等
    脑残错误记录
    博主的OI流水账
    NOI2019游记
    NOI数论姿势瞎总结(Pi也没有)
  • 原文地址:https://www.cnblogs.com/jiangfeilong/p/10061034.html
Copyright © 2020-2023  润新知