For the implementation of another CR (6484965: G1: piggy-back liveness accounting phase on marking) we need to be able to calculate the size of an object whose to-space image we mark during a GC. This is currently quite tricky given that if the object is already forwarded by another worker we cannot guarantee that the to-space image of said object is consistent (the other worker might still be in the process of copying the object, so when we try to read its to-image header we might get back junk).
One idea round this is to read the size from the object's from-image. This works most of the time apart from the case of chunked object arrays. For those we use the from-image length field to store the sarting index of the next chunk to process (and restore the real length when after we claim the last chunk). But, when we read such an array, we cannot be sure whether the length is the actual length or the next index.
The solution propose here to deal with the case of chunk object arrays is to always encode the index so that it is always negative before we store it in the from-image length field. We can easily do this with the following: -(index + 1) (+1 so that 0 is also encoded as a negative value). This way we can distinguish whether the length is really a valid length (>=0) or an encoded index (<0). In the latter case, and by being careful to only store the encoded index after we finish copying the object, we can simply read the correct length from the to-image of the object.
It turns out that the idea of using a negative value to encode the next index (in the length field of the from-image) does not work as it introduces a subtle race (see the Evaluation section for the details).
The alternative we'll try is to use the length field of the to-image (instead of the from-image) to keep track of the next index. This way, the from-image will always be consistent and we'll always be able to read the correct size from it.