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 2047
半阙折子戏
半阙折子戏 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条回答
  •  無奈伤痛
    2021-02-01 01:19

    Source:

    https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.21.3

    The short answer is, looking at the java 8 specification: No.

    The == operator will always perform object equality check (given that neither reference is null). Even if the object is moved, the object is still the same object.

    If you see such an effect, you have just found a JVM bug. Go submit it.

    It could, of course, be that some obscure implementation of the JVM does not enforce this for whatever strange performance reason. If that is the case, it would be wise to simply move on from that JVM...

提交回复
热议问题