Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Enum static method thread safety?

Tags:

java

enums

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;
    }
}
like image 493
Aruna Karunarathna Avatar asked Dec 23 '22 00:12

Aruna Karunarathna


1 Answers

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

like image 196
Lino Avatar answered Jan 04 '23 23:01

Lino