0

I have coded a simple program to understand how VisualVM works. Here is the full code:

package memorygames;
public class MemoryGames
{
   static class A {
       private int i;
       private String s;

       A(int i, String s)
       {
           this.i = i;
           this.s = s;
       }

       public int getI()
       {
           return i;
       }

       public String getS()
       {
           return s;
       }
   }

    public static void main(String[] args) {
        A a = new A(23, "hello");
        while(true) {
            System.out.println(a.getS());
            try
            {
                Thread.sleep(1000);
            }
            catch (InterruptedException e)
            {
                e.printStackTrace();
            }
        }
    }
}

Now I make a HeapDump of my application in VisualVM. I see the instance of my 'A' class, but the s variable is empty! Its value equal to null. 'i' variable holds the correct value of 23.

Why this happens?

UPDATE: May be I am misusing the VisualVM? Here is my screenshot: http://oi42.tinypic.com/2091qfl.jpg

UPDATE: Not sure, but probably this was a result of some memory optimization. I have added

 while(true) {
            a.setS(new String("a-setter " + Math.random()));
            (...)
}

... and now I can see the string value in the variable. I wonder do other people could really see the results in the Heap different from mine.

KutaBeach
  • 1,445
  • 21
  • 43

1 Answers1

0

It could be a problem of the JDK you are using to run your example. Can you try different version of JDK? JDK 7u40 or JDK 8 preview build? It works for me using JDK 7u40.

Tomas Hurka
  • 6,723
  • 29
  • 38
  • Here is my version, will look for another: java version "1.6.0_33" Java(TM) SE Runtime Environment (build 1.6.0_33-b03-424-11M3720) Java HotSpot(TM) 64-Bit Server VM (build 20.8-b03-424, mixed mode) – KutaBeach Sep 26 '13 at 12:15
  • Please try JDK 7u40. I do remember that sometimes string constants are not part of the heap dump. – Tomas Hurka Sep 27 '13 at 07:08
  • Hi @TomasHurka can you please elaborate on the string constants not being part of the heap dump? I'm seeing some strange null values for strings in a heap dump (Java 6) and I'd like to find an authoritative reference that describes this. Thanks! – Greg Mattes May 05 '14 at 20:07