aspose file tools*
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


Win a copy of Spring in Action this week in the Spring forum!
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
Author

How many value of x are there?

azuki ooh
Greenhorn

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?

Thanks!
Jeff Verdegan
Bartender

Joined: Jan 03, 2004
Posts: 6109
    
    6

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: http://aspose.com/file-tools
 
subject: How many value of x are there?