Create WeakReference in Java

Description

The following code shows how to create WeakReference.

A weak reference is used to determine when an object is no longer being referenced.

Example


// w ww  .j a va2 s.c  o  m
  


import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;

public class Main {
  public static void main(String[] argv) throws Exception {
    ReferenceQueue rq = new ReferenceQueue();
    WeakReference<String> wr = new WeakReference<String>("string", rq);

    while (true) {
      Reference r = rq.remove();
      if (r == wr) {
        System.out.println("no longer referenced");
      }
    }
  }
}

The code above generates the following result.





















Home »
  Java Tutorial »
    Development »




Java Algorithms
Java Clipboard
Java Compiler
Java Desktop
Java Virtual Machine
Java Math
OS
Random
Java Robot
Java RuntimeMXBean
Java Timer
Java UUID
Java Internationalization