Can the JVM GC move objects in the middle of a reference comparison, causing a comparison to fail even when both sides refer to the same object?

后端 未结 8 1939
半阙折子戏
半阙折子戏 2021-02-01 00:36

It\'s well known that GCs will sometimes move objects around in memory. And it\'s to my understanding that as long as all references are updated when the object is moved (before

8条回答
  •  -上瘾入骨i
    2021-02-01 00:58

    Java object hold a reference to the "object" not to the memory space where the object is stored.

    Java do this because it allow the JVM to manage memory usage by its own (e.g. Garbage collector) and to improve global usage without impacting the client program directly.

    As instance for improvement, the first X int (I don't remember how much) are always allocated in memory to execute for loop fatser (ex: for (int i =0; i<10; i++))

    And as example for object reference, just try to create an and try to print it

    int[] i = {1,2,3};
    System.out.println(i);
    

    You will see that Java returning a something starting with [I@. It is saying that is point on a "array of int at" and then the reference to the object. Not the memory zone!

提交回复
热议问题