Java Enum static method thread safety?

Aruna Karunarathna :

I have a use case where, iterating the Java enum and test, the argument contain in the enum list, It's a static method, Is this thread safe?

public enum EnumType {

    ONE,
    TWO,
    THREE,
    FOUR,
    FIVE;

    public static boolean isValid(String input) {
        for (EnumType type : EnumType.values()) {
            if (input.equals(type.toString())) {
                return true;
            }
        }
        return false;
    }
}
Lino :

EnumType.values() returns a copy of all enum constants, so even if you would modify the array returned by values() it would not influence any other threads.

The byte code confirms this:

public static values()[Lcom/example/EnumType;
 L0
  LINENUMBER 43 L0
  GETSTATIC com/example/EnumType.$VALUES : [Lcom/example/EnumType;
  INVOKEVIRTUAL [Lcom/example/EnumType;.clone ()Ljava/lang/Object;
  CHECKCAST [Lcom/example/EnumType;
  ARETURN
  MAXSTACK = 1
  MAXLOCALS = 0

The line:

INVOKEVIRTUAL [Lcom/example/EnumType;.clone ()Ljava/lang/Object;

Invokes the Array.clone() method, which returns a shallow copy of the array

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=72887&siteId=1