强引用(Strong references)是使用最普遍的引用。如果一个对象具有强引用,那么垃圾回收器绝不会回收它,即便内存不足JVM也会选择抛出OutOfMemoryErro,强行终止程序也不会随意回收具有强引用的对象来解决内存不足的问题。
String s = new String(“opps”);这种形式的引用成为强引用,它有以下特点:
- 强引用可以直接访问目标对象.
- 强引用所指向的对象在任何时候都不会被系统回收.
- 由于2的原因,强引用可能导致内存泄露.
publicclass ClassStrong {
publicstaticclass Referred {
protectedvoid finalize() {
System.out.println("Good bye cruel world");
}
}
publicstaticvoid collect() throws InterruptedException {
System.out.println("Suggesting collection");
System.gc();
System.out.println("Sleeping");
Thread.sleep(5000);
}
publicstaticvoid main(String args[]) throws InterruptedException {
System.out.println("Creating strong references");
// This is now a strong reference.
// The object will only be collected if all references to it disappear.
Referred strong = new Referred();
// Attempt to claim a suggested reference.
ClassStrong.collect();
System.out.println("strong="+strong);
System.out.println("Removing reference");
// The object may now be collected.
strong = null;
ClassStrong.collect();
System.out.println("strong="+strong);
System.out.println("Done");
}
}
Output:
Creating strong references
Suggesting collection
Sleeping
strong=ClassStrong$Referred@c17164
Removing reference
Suggesting collection
Sleeping
Good bye cruel world
strong=null
Done
只有当设置实例strong为null时才会调用gc的finalize方法,从而强制回收.