This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
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 Murach's Java Servlets and JSP this week in the Servlets 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

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.
jQuery in Action, 2nd edition
subject: How many value of x are there?
Similar Threads
++ and += implementaion
Post increment
increment operator
Bowled over by a simple code
unary operator