File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Threads and Synchronization and the fly likes i++ is not a singular operation Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "i++ is not a singular operation"?" Watch "i++ is not a singular operation"?" New topic

i++ is not a singular operation"?

Ziyang Zhang
Ranch Hand

Joined: Jul 17, 2010
Posts: 47

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


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

Enjoy life!
Mike Simmons
Ranch Hand

Joined: Mar 05, 2008
Posts: 3028
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

Joined: Mar 28, 2003
Posts: 11777

You might also be interested in Debugging Threads with a Little Help from javap - same basic problem, just approached from a different direction.

The Sun Certified Java Developer Exam with J2SE 5: paper version from Amazon, PDF from Apress, Online reference: Books 24x7 Personal blog
Henry Wong

Joined: Sep 28, 2004
Posts: 20521

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.


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Lester Burnham

Joined: Oct 14, 2008
Posts: 1337
Also check out the java.util.concurrent.atomic package, particularly AtomicInteger for this case. It does have atomic (and thus thread-safe) increment.
I agree. Here's the link:
subject: i++ is not a singular operation"?
It's not a secret anymore!