Types of References in Java


There are four different kinds of references based on the way in which the data is garbage collected.

  • Strong references
  • Weak references
  • Soft references
  • Phantom references

Strong reference

It is the default type of reference object. An object that has active strong reference can’t be garbage collected. It is possible only if the variable that is strongly referenced points to null. Let us see an example −

Example

class Demo {
   //Some functionality
}
public class Demo_example{
   public static void main(String[] args){
      Demo my_inst = new Demo();
      my_inst = null;
   }
}

Weak reference

They are not default class of reference object, hence need to be explicitly specified. It is generally used with WeakHashmap, so as to reference entry objects. Such weak references are marked for garbage collection by the Java Virtual Machine. Such references are created using the ‘java.lang.ref.WeakReference’ class.

Let us see an example −

Example

 Live Demo

import java.lang.ref.WeakReference;
class Demo{
   public void display_msg(){
      System.out.println("Hello");
   }
}
public class Demo_sample{
   public static void main(String[] args){
      Demo inst = new Demo();
      inst.display_msg();
      WeakReference<Demo> my_weak_ref = new WeakReference<Demo>(inst);
      inst = null;
      inst = my_weak_ref.get();
      inst.display_msg();
}

Output

Hello
Hello

A class named Demo has a function named ‘display_msg’. This function displays a relevant message. In another class named ‘Demo_sample’, the main function is defined, and an instance of Demo class is created. The ‘display_msg’ function is called on the instance. A weakReference to the Demo class is created, and the Demo insatne is assigned to null, and the function is called on it again. The relevant output is displayed on the console.

Updated on: 17-Aug-2020

672 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements