dimanche 29 janvier 2017

Is switch operator volatile?

In documentation it is said you could equally use if-else multiple times or switch-case:

int condition;

setCondition(int condition) {
    this.condition = condition;
}

Either switch-case

switch (condition) {
  case 1: print("one"); break;
  case 2: print("two"); break;

or

if (condition == 1) { print("one"); }
else if (condition == 2) { print("two"); }

Next, conditionis declared volatile and method setCondition() is called from multiple threads. If-else is not atomic and volatile variable write is a synchronizing action. So both "one" and "two" string could be printed in the last code.

It could be avoided if some method local variable with initial value was used:

int localCondition = condition;
if (local condition == ..) ..

Does switch-case operator hold some initial copy of variable? How are cross threads operations implemented with it?

Aucun commentaire:

Enregistrer un commentaire