软引用和虚引用的示例?
软引用通常用于实现对内存敏感的缓存。让我们来看一个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”函数。相关输出显示在控制台上。
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP