Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

import java.lang.ref.WeakReference;
import java.util.Iterator;
import java.util.Map;
import java.util.WeakHashMap;

public class Main {
    public static void main(String[] argv) throws Exception {
        Object keyObject = "";
        Object valueObject = "";
        Map weakMap = new WeakHashMap();

        weakMap.put(keyObject, valueObject);
        WeakReference weakValue = new WeakReference(valueObject);

        weakMap.put(keyObject, weakValue);

        Iterator it = weakMap.keySet().iterator();
        while (it.hasNext()) {
            Object key = it.next();
            weakValue = (WeakReference) weakMap.get(key);
            if (weakValue == null) {
                System.out.println("Value has been garbage-collected");
            } else {
                System.out.println("Get value");
                valueObject = weakValue.get();
            }
        }
    }
}