Memory Management in Java: Weak references

              Reference is a pointer which points to another variable or pointer. It plays a vital role in memory management. It deals with the access of data.

Depends on the reference, it may be strong or weak. A strong reference prevents the garbage collector to reclaim the object memory until the reference exists.

A weak reference allows the garbage collector to reclaim the object memory.

Note: Weak reference is used in memory sensitive type of applications.

Let us create a java memory management program to implement the weak reference example.

Java implementation of weak references:

This program has the following logic.

Logic:

  • ·       A string object is created as Strong object reference.
  • ·       It gets assigned with a value.
  • ·       A weak reference is created as like strong reference.
  • ·       Get the weak reference.
  • ·       Assign the strong reference as null.
  • ·       Make the system to call the garbage collector.
  • ·       If you get the value of weak reference, it become null.

Program:

//Built-in packages are included.

import java.lang.ref.WeakReference;

//class with main() function

public class WeakReferenceEg {

    public static void main(String[] args) {

        String sReference = new String("Welcome to the world of Java Programming");

        // Let us create a weak reference using Strong reference

        WeakReference<String> wReference = new WeakReference<>(sReference);

       // Get the the reference

        System.out.println("Get the reference: " + wReference.get());

      // make the strong reference as null

        sReference = null;

      // Garbage collection is done

        System.gc();

      // final result after garbage collection

        System.out.println("Final reference value: " + wReference.get());

    }

}

Output:

When you compile and execute the above program, you get the below output.

C:\raji\blog>javac WeakReferenceEg.java

C:\raji\blog>java WeakReferenceEg

Get the reference: Welcome to the world of Java Programming

Final reference value: null

This is the sample java program to implement the weak reference is executed successfully. Hope this blog post is useful for you. Keep Coding!!!

No comments:

Post a Comment