Thinking in Java(8)-inheritance and cleanup
来源:互联网 发布:python 月份加减 编辑:程序博客网 时间:2024/05/16 01:37
大家都知道,在继承中,不共享变量时,Java类对象initialize的顺序和cleanup的顺序相反,但是共享变量时情况就比较复杂了,这时使用一个final变量跟踪引用是一个好方法,可以清楚地看到对象的initialize和cleanup情况:
class Shared{ private int refcount = 0; private static long counter = 0; private final long id = counter++; public Shared () { System.out.println(" Creating" + this); } public void addRef() { refcount++; } protected void dispose() { if (--refcount == 0) System.out.println("Disposing " + this); } public String toString() { return ("Shared " + id); } protected void finalize() { if(refcount != 0) System.out.println("Error: object is not properly cleaned-up!");}}class Composing{ private Shared shared; private static long counter = 0; private final long id = counter++; public Composing(Shared shared) { System.out.println("Creating " + this); this.shared = shared; this.shared.addRef(); } protected void dispose() { System.out.println("disposing " + this); shared.dispose(); } public String toString() { return ("Composing " + id ); }}public class ReferenceCounting { public static void main(String[] args) { // TODO Auto-generated method stub Shared shared = new Shared(); Composing[] composing = {new Composing(shared),new Composing(shared),new Composing(shared),new Composing(shared) ,new Composing(shared)}; for (Composing c : composing) c.dispose(); System.gc(); // Verify failure: new Composing(new Shared()); System.gc(); }}
1 0
- Thinking in Java(8)-inheritance and cleanup
- thinking in java(V)--composition and inheritance
- thinking in java(III)--initialization and cleanup
- Thinking in Java(6)-combinning composition and inheritance
- Thinking in Java(7)-Guaranteeing proper cleanup
- 看了thinking in java 的initialize and cleanup 的一点总结
- Default Methods in Java 8 and Multiple Inheritance
- Multiple Inheritance in Java and Composition vs Inheritance
- Cleanup总结---Thinking in java 英文版部分小结
- Thinking in Java 8
- Thinking in java (RTTI And Reflection)
- Thinking in Java(9)-closures and callbacks
- Inheritance in Java
- 【学习笔记】Thinking in java (第三版)第四章 初始化和清除(Initialization & Cleanup)
- 处理教材:Initialization & Cleanup of "Thinking in Java"
- Prototypes and Inheritance in JavaScript
- Prototypes and Inheritance in JavaScript
- Thinking in Java笔记8
- <context:component-scan>使用说明
- Nginx代理TCP请求模块添加及配置步骤
- Lintcode 反转整数
- 干货 | 可视化设计:地图四部曲之迁徙图
- java压缩图片内存大小,但不改变分辨率大小,第一种方式
- Thinking in Java(8)-inheritance and cleanup
- 【linux系统】Ubuntu根目录下各文件夹的功能详细介绍
- Koa 请求日志打点工具
- EditeText
- 选用Ibatis和Hibernate的区别
- ios 替换字符串
- 广告轮播+大图相册查看用于商品详情页
- jQuery几点心得
- python之模块二