• Post Reply Bookmark Topic Watch Topic
  • New Topic

static variables and synchronization  RSS feed

 
M Mistroni
Ranch Hand
Posts: 64
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all
i was asked a synchronization question during a java interview......(which i failed btw)...
question was
suppose i have following class



There is a main thread which creates 10 instances of MyThread and start them.
- What are the possible values you see on the screen ?
- What is the minimum value you see
- What is the max value you see

I said that, as the counter is not synchronized, you will see values oscillating between 1 and potentially 100,. with values potentially
going up and down as thread increment the counter.

He replied (answer that is still bothering me) that the minimum value could be zero... because the JVM could just store the counter variable in
memory and forget about updating it.

I took his answer for granted (as i failed the interview)... but the more i think about it, the more it seems i got it right and he got it completely wrong

The variable is static. why java woudl it put in a memory location and forget about updating it, as the variable is shared between all MyThread instances?

I thought for a moment that he confused himself and forgot that he told me that the variable is static,. But then again, if the variable is not static, each counter
will be cached locally for each thread, and still get incremented.

Could anyone explain me how is it possible that i could see the value zero in the output?

w/kindest regards
Marco














 
Stephan van Hulst
Saloon Keeper
Posts: 7817
142
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can't see 0. The minimum value is always at least 1. Regardless of what happens, the counter is always at least increased by 1 before it is printed.

The minimum value can fluctuate between 1 and 10. If all threads increase the value before it's printed by any of them, the minimum will be 10. Any values in between are possible as well.
The maximum value can fluctuate between 10 and 100. If all threads cache the initial value of counter, each of them will print the numbers 1 to 10. Any maximum value between 10 and 100 is possible as well.
 
Mike Simmons
Ranch Hand
Posts: 3090
14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I agree with Stephan, 0 is impossible. Each thread may or may not be able to see changes made by other threads, but they absolutely will changes made within the same thread. So each thread will print a first number that is >=1, a second number that is >=2, a third that's >= 3, etc. And in the end, among all the threads, there will be at least ten numbers printed which are greater than or equal to 10.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!