Java 中的弱引用類
Sheeraz Gul
2022年5月31日
弱引用是一種強度不足以使物件保留在記憶體中的引用。本教程演示了 Java 中弱引用的使用。
Java 中的弱引用類
在 Java 中,java.lang.ref.WeakReference
類利用垃圾收集器來確定可達性,所以我們不需要自己做。Java 中的弱引用類有以下方法。
方法 | 描述 |
---|---|
get() |
此方法返回引用物件的所指物件。 |
clear() |
該方法用於清除引用物件。 |
enqueue() |
該方法用於將引用物件新增到佇列中;該物件需要在佇列中註冊。 |
isEnqueued() |
這個方法告訴引用物件是否已經入隊;它可以是垃圾收集器或程式本身。 |
首先,讓我們嘗試一個簡單的例子來實現 Java 弱引用類。
package delftstack;
import java.lang.ref.WeakReference;
public class Weak_Reference {
public static void main(String[] args) {
// creating a strong object
Demo_Class Strong_Object = new Demo_Class();
// creating a weak reference of demo_class
WeakReference<Demo_Class> Weak_Object = new WeakReference<>(Strong_Object);
System.out.println("Call the show info function using the strong object");
Strong_Object.Show_Info();
System.out.println("Setting the object to null");
Strong_Object = null;
Strong_Object = Weak_Object.get();
System.out.println( "Call the show info function using the weak object");
Strong_Object.Show_Info();
}
}
class Demo_Class {
void Show_Info() {
System.out.println(">>This is the info from demo class<<");
}
}
上面的程式碼建立了一個 Demo_Class
的強物件和一個同一個類的弱物件,並呼叫 Show_Info
函式。見輸出:
Call the show info function using the strong object
>>This is the info from demo class<<
Setting the object to null
Call the show info function using the weak object
>>This is the info from demo class<<
現在讓我們嘗試使用上述方法的示例。
package delftstack;
import java.lang.ref.WeakReference;
public class Weak_Reference {
public static void main(String[] args) {
Demo_Class Strong_Object = new Demo_Class();
WeakReference<Demo_Class> Weak_Object = new WeakReference<Demo_Class>(Strong_Object);
System.out.println( "Retrieve object from weak reference using get()");
Weak_Object.get().Show_Info();
System.out.println( "queue object using enqueue()");
System.out.println(Weak_Object.enqueue());
System.out.println( "Check if reference is queued using isEnqueued()");
System.out.println(Weak_Object.isEnqueued());
}
}
class Demo_Class {
void Show_Info() {
System.out.println("Show_Info() from Demo_Class is called.");
}
}
上面的程式碼在 Demo_Class
的弱物件上使用了上面描述的所有方法。見輸出:
Retrieve object from weak reference using get()
Show_Info() from Demo_Class is called.
queue object using enqueue()
false
Check if reference is queued using isEnqueued()
false
Author: Sheeraz Gul
Sheeraz is a Doctorate fellow in Computer Science at Northwestern Polytechnical University, Xian, China. He has 7 years of Software Development experience in AI, Web, Database, and Desktop technologies. He writes tutorials in Java, PHP, Python, GoLang, R, etc., to help beginners learn the field of Computer Science.
LinkedIn Facebook