2

Using JDK 1.8 and VisualVM, I saw a string's retained size is 0. According to this article, this means the memory allocated to the string is 0. Does this mean the string has already been GC? If if was already been GC, why does it still display? If not, What does retained size=0 mean? Does it mean "If JVM GC this string, it can only get 0 KB of memory free"?

The example code is:

public class Main {
    private static final Logger LOGGER = Logger.getLogger(Main.class.getName());
    private static ExecutorService executorService = Executors.newFixedThreadPool(3);

    public static void main(String[] args) throws InterruptedException {
        AAAAAAAA a = new AAAAAAAA();

        a.setString();
        Thread.sleep(55555555); // I dump it when it's asleep.
    }
}

class AAAAAAAA {
    String string = "wawawawa";

    public void setString() {
        string = "hahahahaha";
    }
}

enter image description here

guo
  • 9,674
  • 9
  • 41
  • 79

1 Answers1

3

The "retained size" in VisualVM refers to the size that the object would take up in the heap after the next full GC.

In your case, by the time you get to the above Thread.sleep() method, the "wawawawa" string object is eligable for garbage collection (you've set the string field that was holding it to "hahahahaha" instead), so it would take up 0 space after the next full GC. That's what you see in that screenshot.

Michael Berry
  • 70,193
  • 21
  • 157
  • 216
  • Could you please offer a offical doc or link to prove "The "retained size" in VisualVM refers to the size that the object would take up in the heap after the next full GC."? I can't find any when googling "retained size visualvm" – guo Nov 01 '18 at 12:18