noripcord
noripcord

Reputation: 3502

Shouldn't this work? WeakReference not being cleared by GC

class RandomMain {

    static class MyObj{
        public final int i;
        MyObj(int i) { this.i = i;}
    }

    static MyObj m = null;

    public static void main(String[] args) throws Exception {
        m = new MyObj(1);
        final WeakReference<MyObj> a = new WeakReference<>(m);
        final Thread thread = new Thread(() -> {
            int i = 0;
            while(a.get() != null) {
                try {
                    System.out.println("# ("+ (i++) +"): a.get() != null");
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        thread.start();
        new Thread(() -> {
            try {
                Thread.sleep(2500);
                System.out.println("# Will clear static reference to object (m = null)");
                m = null;
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }).start();

        thread.join();
        System.out.println("# Thread: yo' about to die, but your sons will seat at the head of all tables, my boy!");
    }
}

If you run this code, it'll run forever. For me -at least- it does. It doesn't relinquish the reference. As I understand it, the get() method should return null after the static reference has being cleared, right?

Thanks for reading.

Upvotes: 0

Views: 53

Answers (1)

Louis Wasserman
Louis Wasserman

Reputation: 198381

Yes, it would return null after the static reference has been cleared. But why would it clear it? There's no need for the system to run garbage collection; there's plenty of memory.

Calling System.gc() might make a difference, but there's no guarantee of that either.

Upvotes: 3

Related Questions