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 1938
半阙折子戏
半阙折子戏 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...

    0 讨论(0)
  • 2021-02-01 01:25

    No, because that would be flagrantly ridiculous and a patent bug.

    The GC takes a great deal of care behind the scenes to avoid catastrophically breaking everything. In particular, it will only move objects when threads are paused at safepoints, which are specific places in the running code generated by the JVM for threads to be paused at. A thread at a safepoint is in a known state, where the positions of all the possible object references in registers and memory are known, so the GC can update them to point to the object's new address. Garbage collection won't break your comparison operations.

    0 讨论(0)
提交回复
热议问题