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?
finalguarantees 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:
However, it is important to note that the
aarray is not immutable so, for example, you could seta[0] = 10and that update would not be synchronized. But as long as you don’t change any values inayou should be good.