Weak Reference operation check

Check the operation of Java Weak Reference.

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

public class Main {

    static class Entry{
        private final String name;

        public Entry(String name) {
            this.name = name;
        }

        @Override
        public String toString() {
            return name;
        }
    }

    public static void main(String[] args) {
        var val = new Entry("Hello");
        var ref = new WeakReference<>(val);

        System.out.println("ref: "+ val + ", weak-ref: "+ ref.get());

        System.out.println("gc");
        System.gc();

        System.out.println("ref: "+ val + ", weak-ref: "+ ref.get());

        System.out.println("e = null");
        val = null;

        System.out.println("gc");
        System.gc();

        System.out.println("ref: "+ val + ", weak-ref: "+ ref.get());
    }
}

The execution result is as follows.

ref: Hello, weak-ref: Hello
gc
ref: Hello, weak-ref: Hello
e = null
gc
ref: null, weak-ref: null

By the way, var e = "Hello"; But I expected the same result, but it remained without GC.

ref: Hello, weak-ref: Hello
gc
ref: Hello, weak-ref: Hello
e = null
gc
ref: null, weak-ref: Hello

Probably because the code itself holds "Hello", it is highly possible that it was not targeted for GC. Therefore, the same result was obtained by explicitly new as follows.

var e = new String("Hello");

Note that valueOf is cached without permission even when trying with Integer instead of String.

Recommended Posts

Weak Reference operation check
Check the operation using jetty with Maven.
Build TensorFlow operation check environment with Docker
Check the operation of the interface through threads