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;
    }
}
                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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With