Examples of soft references and phantom references?

JavaServer Side ProgrammingProgramming

Soft references are often used to implement memory-sensitive caches. Let us see an example of soft references in Java −

Example

Live Demo

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();
   }
}

Output

Hello there
Hello there

A class named Demo contains a function named ‘display_msg’, that displays the relevant message. Another class named ‘Demo_example’ is defined, that contains the main function. Here, an instance of the Demo class is created, and the ‘display_msg’ function is called on this instance. A SoftReference instance for the Demo class is created, and the instance is assigned to null. The ‘get’ function is called on this softreference object, and assigned to the previous instance. The ‘display_msg’ function is called on this instance. Relevant message is displayed on the console.

Phantom references are often used for scheduling pre-mortem cleanup actions in a more flexible way than possible with the Java finalization mechanism.

Let us now see an example of Phantom References −

Example

 Live Demo

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();
   }
}

Output

Hello there
Exception in thread "main" java.lang.NullPointerException
at Demo_example.main(Demo_example.java:22)

A class named Demo contains a function named ‘display_msg’ that displays a relevant message. Another class named Demo_example contains the main function. This function contains the instance of the Demo class, and the ‘display_msg’ function is called on it. Then, a ReferenceQueue instance is created. Another PhantomReference instance is created and assigned to ‘null’. Then, the previous instance is assigned to null, and then the ‘display_msg’ function is called on this instance. The relevant output is displayed on the console.

raja
Published on 17-Aug-2020 09:08:58
Advertisements