• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

i++ is not a singular operation"?

 
Ziyang Zhang
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


The above is a very simple piece of code.
I think it is reasonable to get some resutl like this:
t2: 0
t1: 0
t2: 1
t1: 2

or

t1: 0
t2: 0
t2: 2
t1: 2

But why in some rare conditions I got the following result?
t1: 0
t2: 0
t1: 1
t2: 1
 
Mike Simmons
Ranch Hand
Posts: 3028
10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Because, as you say, i++ is not a singular operation. Normally we would say, it's not atomic. It really consists of 3 operations:

1. Read the current value of i
2. Add 1 to that value
3. Write the new value of i

If these steps occur simultaneously in different threads, strange things can happen.

Thread A: 1. read i = 0;
Thread A: 2. add 1 - Thread A's local copy of i is now 1
Thread B: 1. read i = 0;
Thread B: 2. add 1 - Thread B's local copy of i is now 1
Thread B: 3. write the new value of i = 1
Thread A: 3. write the new value of i = 1

That's probably what happened in the run you're asking about.
 
Andrew Monkhouse
author and jackaroo
Marshal Commander
Pie
Posts: 11853
185
C++ Firefox Browser IntelliJ IDE Java Mac Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You might also be interested in Debugging Threads with a Little Help from javap - same basic problem, just approached from a different direction.
 
Henry Wong
author
Marshal
Pie
Posts: 20882
75
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

As a side note, there are processors where there is an opcode that increment to memory (and hence, is atomic) -- its just that the JVM doesn't have such a byte code... but in theory, it is possible to have a JIT that will optimize a set of byte codes to such an opcode, and hence, could possibly run with that instruction being atomic.

Also note that it is more than atomic concerns. There are also caching concerns. So, you will also need to declare "i" as volatile, or you may not see the increment, even if it is atomic.

Henry

 
Lester Burnham
Rancher
Posts: 1337
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Also check out the java.util.concurrent.atomic package, particularly AtomicInteger for this case. It does have atomic (and thus thread-safe) increment.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic