Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Varargs, immutable array, and thread-safety

Hi all I have an immutable array implementation which looks like this:

public static final class FixedArray<T> {
    private final T[] array;
    public final int Length;

    @SafeVarargs
    public FixedArray(T... args) {
        array = args;
        Length = args.length;
    }

    public T Get(int index) {
        return array[index];
    }
}

public static final class FixedIntArray {
    private final int[] array;
    public final int Length;

    public FixedIntArray(int... args) {
        array = args;
        Length = args.length;
    }

    public int Get(int index) {
        return array[index];
    }
}

public static final class FixedLongArray {
    private final long[] array;
    public final int Length;

    public FixedLongArray(long... args) {
        array = args;
        Length = args.length;
    }

    public long Get(int index) {
        return array[index];
    }
}

Initially I'd thought that it is guaranteed to be thread-safe. But after reading the discussion regarding immutable arrays and the Java Memory Model, I believe alone, I can't be sure.

I've not used a defensive copy, with the contract that the calling code "does the right thing" (and as usual, if it doesn't follow the contract, the behavior is undefined).

The calling method looks like this:

public static void main(String args[]) {
    int[] ints = new int[10000];
    FixedIntArray fixed_ints = new FixedIntArray(ints);
    SendToThreadA(fixed_ints);
    SendToThreadB(fixed_ints);
    SendToThreadC(fixed_ints);
    SendToThreadD(fixed_ints);
    //caller (which is this method) does the right thing, ints goes out of scope without anyone trying to modify it.
}

I was wondering is the code above guaranteed to be thread-safe?

like image 841
Pacerier Avatar asked Apr 28 '26 00:04

Pacerier


1 Answers

As we don't know what happens to the array (and its values) to which you store a reference, I think your classes would be much safer if the constuctors create a copy of the argument array and set the internal final reference to the copied array.

like image 75
rsp Avatar answered Apr 29 '26 13:04

rsp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!