java基礎教學欄位介紹Java"弱" 引用
Java裡一個物件obj被創建時,被放在堆裡。當GC運作的時候,發現沒有任何引用指向obj,那麼就會回收obj物件的堆記憶體空間。換句話說,一個物件被回收, 必須滿足兩個條件:
(1)沒有任何引用指向它(2) GC被運行。 在實際開發中,我們可以透過把所有指向某個物件的referece置空來保證這個物件在下次GC運行的時候被回收,類似下面:Object c = new Car(); c=null;
Object c = new Car(); //只要c还指向car object, car object就不会被回收 -->(强引用)
public class Car { private double price; private String color; public Car(double price, String color) { this.price = price; this.color = color; } public double getPrice() { return price; } public String getColor() { return color; } public String toString() { return "This car is a " + this.color + " car, costs $" + price; } }
public class WeakReferenceCar extends WeakReference<Car> { public WeakReferenceCar(Car car) { super(car); } }
public static void main(String[] args) { Car car = new Car(2000.0, "red"); WeakReferenceCar wrc = new WeakReferenceCar(car); wrc.setStr("111"); int i = 0; while (true) { if (wrc.get() != null) { i++; System.out.println("WeakReferenceCar's Car is alive for " + i + ", loop - " + wrc); } else { System.out.println("WeakReferenceCar's Car has bean collected"); break; } } }
WeakReferenceCar's Car is alive for 68450, loop - interview.WeakReferenceCar@776ec8df WeakReferenceCar's Car is alive for 68451, loop - interview.WeakReferenceCar@776ec8df WeakReferenceCar's Car is alive for 68452, loop - interview.WeakReferenceCar@776ec8df WeakReferenceCar's Car is alive for 68453, loop - interview.WeakReferenceCar@776ec8df [GC (Allocation Failure) [PSYoungGen: 34304K->1000K(38400K)] 34320K->1016K(125952K), 0.0015129 secs] [Times: user=0.02 sys=0.02, real=0.00 secs] WeakReferenceCar's Car is alive for 68454, loop - interview.WeakReferenceCar@776ec8df WeakReferenceCar's Car has bean collected Heap PSYoungGen total 38400K, used 1986K [0x00000000d5e00000, 0x00000000da900000, 0x0000000100000000) eden space 33280K, 2% used [0x00000000d5e00000,0x00000000d5ef6b70,0x00000000d7e80000) from space 5120K, 19% used [0x00000000d7e80000,0x00000000d7f7a020,0x00000000d8380000) to space 5120K, 0% used [0x00000000da400000,0x00000000da400000,0x00000000da900000) ParOldGen total 87552K, used 16K [0x0000000081a00000, 0x0000000086f80000, 0x00000000d5e00000) object space 87552K, 0% used [0x0000000081a00000,0x0000000081a04000,0x0000000086f80000) Metaspace used 3547K, capacity 4564K, committed 4864K, reserved 1056768K class space used 381K, capacity 388K, committed 512K, reserved 1048576K
以上是都來看看 Java 中的 '弱' 引用是什麼?的詳細內容。更多資訊請關注PHP中文網其他相關文章!