神奇好望角 The Magical Cape of Good Hope

庸人不必自扰,智者何需千虑?
posts - 26, comments - 50, trackbacks - 0, articles - 11
  BlogJava :: 首页 ::  :: 联系 :: 聚合  :: 管理

Java 中对象引用的类型

Posted on 2007-12-02 20:43 蜀山兆孨龘 阅读(1252) 评论(0)  编辑  收藏
Java 中对象引用的类型 Object Reference Types in Java
  弱引用早有耳闻,但从来没去认真看过。前天改编陈维雷先生的下雪动画时,发现他使用了弱引用,于是趁机把 Java 的对象引用类型看了个究竟。     I've heard of weak reference for a long time, but have never study it seriously yet. The day before yesterday, when I was modifying Mr. William Chen's snowing animation, I saw weak reference was utilized, and then took the chance to read the details of Java's reference type.
  除了通常意义下的强引用,包 java.lang.ref 还定义了其他三种平时不太用到的引用:软引用、弱引用和虚引用,但 API 文档的解释比较含糊。我在网上搜到了一些资料,简单归纳一下。     Except the strong reference of common purpose, package java.lang.ref defines three other references which are less often used: soft reference, weak reference and phantom reference, but they have obscure explanations in the API documention. I searched online and got some stuffs and here are my summaries.
  强引用。当一个对象具有强引用时,Java 虚拟机宁愿抛出 OutOfMemeryError,也绝不让垃圾回收器回收它。     Strong Reference. When an object holds strong references, Java Virtue Machine would rather throw an OutOfMemeryError than let garbage collector (GC) collect it.
  软引用。当一个对象只具有软引用时,垃圾回收器只在内存不足的时候才回收它。     Soft Reference. When an object holds only soft references, GC collects it only if there is not enough memory.
  弱引用。当一个对象只具有弱引用时,一旦被垃圾回收器发现就会被回收。因为垃圾回收器是一个优先级很低的线程,所以弱引用对象也不一定会马上就会被回收。     Weak Reference. When an object holds only weak references, GC collects it as soon as finds it. GC is a thread of very low priority, so a weak reference object may not be collected immediately.
  虚引用。虚引用和对象的生命周期无关。虚引用必须和引用队列联合使用,对象将被回收前,其虚引用将被加入到引用队列。虚引用只是用来监视对象的回收。     Phantom Reference. Phantom reference has nothing to do with the life cycle of an object. Phantom reference must be used together with reference queue, and the object's phantom reference will be added into that reference queue right before collected. Phantom reference is only used to monitor object collecting.
  从以上是否能看出,一个对象不能同时具有软引用和弱引用?     From above shall we say that an object can't have a soft reference and a weak reference at the same time?

只有注册用户登录后才能发表评论。


网站导航: