Possible Duplicate:
How thread-safe is enum in java?
Let there be an enum class like
public enum Type
{
ONE, TWO, THREE, FOUR
}
Is the Type.values() array thread safe to access in a for loop, e.g., in a static method? For example:
public static void process()
{
for (Type type:Type.values())
{
// Do something
}
}
Furthermore, if one defines a static array variable with any subset of these values, will that be thread safe to read? For example:
public static final Type[] TYPES = new Type[] {TWO, THREE};
public static void process()
{
for (Type type:TYPES)
{
// Do something
}
}
In both cases, the process() method may belong to a different class than the definition of the Type enum and of the types array.
Also, the TYPES array could be defined once in the Type enum and returned by a static method of that enum.
So, given the above, if multiple threads are running the process() method simultaneously, will the code be thread safe (at least for just reading the values of the TYPES array)?
Others have already pointed out that the
values()method returns a new array each time, so it is thread safe.However, to answer your second question:
No. Any
public staticarray is not safe, because array elements are always mutable.That is, any thread could change
TYPES[0]to be any otherType, which is not safe in the presence of multiple threads — or indeed even in a single-threaded program.Much better would be to expose a
List<Type>, which can then be safely made immutable (e.g., usingCollections.unmodifiableList()).