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 How many value of x are there? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "How many value of x are there?" Watch "How many value of x are there?" New topic

How many value of x are there?

azuki ooh

Joined: Nov 07, 2008
Posts: 20
If two threads execute the below method increment() concurrently, how many different final values of X are there? You may assume that initially X has value 0.

void increment()
int temp = x;
temp = temp + 1;
x = temp;

I think it's 2. Can someone please help to verify?

Jeff Verdegan

Joined: Jan 03, 2004
Posts: 6109

There's the main memory version. Then either or both of the threads may (or may not) have a cached version. We don't know when the threads will run, and we don't know when they'll read the main version or if or when they'll write it. There could be one value, if both threads read 0 from main and write 1 back to it. Or there could be 2 values, 0 and 1 or 1 and 2, where the smaller value is held in main mem and one thread's cache, and the larger value is in the other thread's cache.
I agree. Here's the link:
subject: How many value of x are there?
It's not a secret anymore!