Java object is gc-ed when it's still linked with a strong reference and a weaked reference

zhuj9 :

Here I have an example:

import java.lang.ref.WeakReference;

public class WeakRefTest {
    public static void main(String[] args) {
        Object obj = new Object();
        WeakReference<Object> weakRef = new WeakReference<Object>(obj);
        int i = 0;
        while (true) {
            if (weakRef.get() != null) {
                i++;
                System.out.println("The object is alive for " + i + " loops - " + weakRef);
            } else {
                System.out.println("The object has been collected.");
                break;
            }
        }
    }
}

When running this program, we'll get output with "The object has been collected." after a while, which means the object will be gc-ed.

However, there is still a strong reference named "obj" linked to the object, how can it be reclaimed? Because JVM found there is no strong reference usage later, so it's not strong reachable?

Nicktar :

Since your loop is running quite "hot" in terms of resource usage, the JVM will want to optimize it. Doing so might point the compiler to the fact that in fact the strong reference can't be reached after entering the loop and thus optimize it away.

This behaviour will likely change if you add something like System.out.println(obj) after your loop. You might need to tweak your loop condition so that the compiler can't see that the new statement is in fact unreachable code... (something like while (weakRef.get() != null))

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=414657&siteId=1