Java.lang.ref.WeakReference is a class in the Java language that allows us to create objects that can be easily collected by the garbage collector whenever needed. It is used to create references to objects that are not being used by any other part of the program.
Here is an example of using WeakReference in Java:
import java.lang.ref.WeakReference;
public class Example {
public static void main(String[] args) {
String name = new String("John");
WeakReference weakName = new WeakReference(name);
name = null;
System.gc();
System.out.println(weakName.get());
}
}
This example creates a string object named "John". Then it creates a WeakReference to that object called "weakName". Then it sets the original "name" variable to null and triggers the garbage collector. Finally, it attempts to print out the value of "weakName". Since the "name" variable has been collected, "weakName" should return a null value.
This package belongs to the Java Standard Library.
Java WeakReference - 30 examples found. These are the top rated real world Java examples of java.lang.ref.WeakReference extracted from open source projects. You can rate examples to help us improve the quality of examples.