軟引用和虛引用的示例?
軟引用通常用於實現對記憶體敏感的快取。讓我們來看一個Java中軟引用的示例:
示例
import java.lang.ref.SoftReference; class Demo{ public void display_msg(){ System.out.println("Hello there"); } } public class Demo_example{ public static void main(String[] args){ Demo my_instance = new Demo(); my_instance.display_msg(); SoftReference<Demo> my_softref = new SoftReference<Demo>(my_instance); my_instance = null; my_instance = my_softref.get(); my_instance.display_msg(); } }
輸出
Hello there Hello there
名為Demo的類包含一個名為“display_msg”的函式,該函式顯示相關訊息。定義了另一個名為“Demo_example”的類,其中包含main函式。在這裡,建立了Demo類的例項,並在該例項上呼叫了“display_msg”函式。建立了Demo類的SoftReference例項,並將該例項賦值為null。“get”函式在該軟引用物件上被呼叫,並賦值給之前的例項。“display_msg”函式在這個例項上被呼叫。相關訊息顯示在控制檯上。
虛引用通常用於以比Java終結機制更靈活的方式排程事後清理操作。
現在讓我們來看一個虛引用的示例:
示例
import java.lang.ref.*; class Demo{ public void display_msg(){ System.out.println("Hello there"); } } public class Demo_example{ public static void main(String[] args){ Demo my_instance = new Demo(); my_instance.display_msg(); ReferenceQueue<Demo> refQueue = new ReferenceQueue<Demo>(); PhantomReference<Demo> phantomRef = null; phantomRef = new PhantomReference<Demo>(my_instance,refQueue); my_instance = null; my_instance = phantomRef.get(); my_instance.display_msg(); } }
輸出
Hello there Exception in thread "main" java.lang.NullPointerException at Demo_example.main(Demo_example.java:22)
名為Demo的類包含一個名為“display_msg”的函式,該函式顯示相關訊息。另一個名為Demo_example的類包含main函式。此函式包含Demo類的例項,並在其上呼叫“display_msg”函式。然後,建立ReferenceQueue例項。建立另一個PhantomReference例項並賦值為“null”。然後,將之前的例項賦值為null,然後在該例項上呼叫“display_msg”函式。相關輸出顯示在控制檯上。
廣告