Is switch operator atomic? Is switch operator atomic? multithreading multithreading

Is switch operator atomic?


From the Java specification on switch statements:

When the switch statement is executed, first the Expression is evaluated. [...]

This suggests that the expression is evaluated once and that the result is temporarily kept somewhere else, and so no race-conditions are possible.

I can't find a definite answer anywhere though.


A quick test shows this is indeed the case:

public class Main {  private static int i = 0;  public static void main(String[] args) {    switch(sideEffect()) {      case 0:        System.out.println("0");        break;      case 1:        System.out.println("1");        break;      default:        System.out.println("something else");    }    System.out.println(i); //this prints 1  }  private static int sideEffect() {    return i++;  }}

And indeed, sideEffect() is only called once.


The expression is evaluated once when entering the switch.

The switch may use the result internally as many times as it needs to determine what code to jump to. It's akin to:

int switchValue = <some expression>;if (switchValue == <some case>)    <do something>else if (switchValue == <some other case>    <do something else>// etc

Actually, a switch compiles to a variety of byte code styles depending on the number of cases and the type of the value.

The switch only needs to evaluate the expression once.