javaarraysmultithreadinginitializationfinal

multiple threads access array


class EverythingMustBeInAClass
{
    private final int i = 42;
    private final int[] a = {2, 3, 5, 7, 11, 13, 17, 19};
}

The fact that i is declared final guarantees that all threads see the same int value 42 (instead of 0).

The fact that a is declared final guarantees that all threads see the same array reference.

But how do I make sure that all threads see the same array elements (instead of 0s)? Do I have to synchronize access to the array, even if I never intend to change the array elements later on?


Solution

  • final guarantees not only that the array reference is seen but also that the object itself has been fully constructed and initialized. So the values in the array will also be seen by all threads.

    Here's a good link on the subject: Thread-safety with the Java final keyword

    To quote:

    The fields on any object accessed via a final reference are also guaranteed to be at least as up to date as when the constructor exits.

    However, it is important to note that the a array is not immutable so, for example, you could set a[0] = 10 and that update would not be synchronized. But as long as you don't change any values in a you should be good.