Mik378
Mik378

Reputation: 22181

Increment operation mechanism

As many developers know, increment operator isn't atomic.

For instance:

public void incrementId(){ // id being an int field
   id++;
}

Actually, this corresponds to three distinct operations:

int temp = id;
id = id + 1;  
id = temp;

Besides, this method behaves similarly:

    public void incrementId(){ // id being an int field
       id = id + 1;  // three steps also here
    }

My question is:

What is the real difference behind the scene between following both operations:

id = id + 1; //three steps => non atomic

id = anotherIntVariable + 1; // one step => atomic

What concept forces the compiler to translate the first one into 3 steps and not the other?

Upvotes: 0

Views: 104

Answers (2)

amit
amit

Reputation: 178471

What concept forces the compiler to translate the first one into 3 steps and not the other?

it is not, id = xyz + 1 will be compiled to the following byte code:

 7  iload_2 [xyz]
 8  iconst_1
 9  iadd
10  istore_1 [id]

It is easy to see from the byte code that the above is not "one step"

Upvotes: 2

Ravi Wallau
Ravi Wallau

Reputation: 10493

There is nothing saying that this:

id = anotherVariable + 1

Will not be performed in 3 steps. But no matter how many times you run the code above, the end result will always be the same (the value of the variable id will always be whatever was on anotherIntVariable plus 1), as in the example id = id + 1, the previously set value on the id variable drives the new id value, and the end value of id might not be what you are expecting if you experience race conditions.

A few notes:

  • If you are setting the id variable from multiple threads, no matter how you are setting it, you need to synchronize it. Always, or else the value might not be set at all (see chapter 3 of Java Concurrency in Practice). Alternatively, you can make the id variable volatile;
  • This only matters if id can actually be accessed from multiple threads. If that is not the case (for example, if id is a local variable in a method), then you don't need to worry about locking/ etc... This holds true even if you have anonymous threads in a method, as they can only access local variables that are declared final.

Upvotes: 1

Related Questions