Primitive Queue<any T> considerations

Timo Kinnunen timo.kinnunen at
Wed Nov 18 19:15:56 UTC 2015


That’s a good question. How would arbitrary-sized values be assigned into an array without any other thread observing the value halfway between two states with its invariants not holding? 

As is mentioned in the JLS in 17.6: “One consideration for implementations of the Java Virtual Machine is that every field and array element is considered distinct; updates to one field or element must not interact with reads or updates of any other field or element.” This probably has to be weakened in the same way as non-atomic reads/writes of long.

Sent from Mail for Windows 10

From: Vitaly Davidovich
Sent: Wednesday, November 18, 2015 19:56
To: MacGregor, Duncan (GE Energy Management)
Cc: valhalla-dev at
Subject: Re: Primitive Queue considerations

As discussed upthread, how would that operation be atomic for arbitrarily
sized value types?

On Wed, Nov 18, 2015 at 1:53 PM, MacGregor, Duncan (GE Energy Management) <
duncan.macgregor at> wrote:

> On 18/11/2015, 16:22, "valhalla-dev on behalf of Dávid Karnok"
> <valhalla-dev-bounces at on behalf of akarnokd at>
> wrote:
> >Let's assume I have a value type named cell:
> >
> >valuetype Cell<any T> {
> >   public T value;
> >   public int mark;
> >}
> >
> >and a power-of-2 array of cells:
> >
> >Cell<any T>[] array;
> >
> >
> >having Cell with final fields is useless here because then I have a
> >constant array and not a queue.
> Maybe I¹m not following you here but the fact fields on a Cell are final
> does not stop you from replacing one Cell in array with a new Cell, just
> as you can replace individual ints in an array of ints.
> So you offset method would be more like
> offset = producerIndex & (array.length - 1)
> if (array[offset].mark != 0) {
>     return false;
> }
> array[offset] = Cell(value, 1);
> producerIndex++;
> return true;
> And that operation on the array will be guaranteed to be atomic (though
> probably needs a compare and swap in case another thread is trying to do
> the same thing).
> Duncan.

More information about the valhalla-dev mailing list