I have doubt regarding the following code:
The source of it is http://www.certpal.com -> Concurency-> Question nr 6
I thought that the answer is 0 1 2 0 1 2 , but the author says :
"There are 2 threads in action and both of them have access to the var variable since it is static.
Both of them instantiate the counter to 0. There is no change in the value of the var variable.The output cannot be guaranteed since
there is no synchronization to go with the execution.There is nothing to prevent both threads from accessing gun at the same time."
I think this is wrong because the threads object are constructed using two different instances of the Trans (line 1 and 2)
Also I run the program and the output was 0 1 2 0 1 2
Rein de Boer wrote:because var is static, all the different instances access the same variable, so the explanation is right.
I agree with you, but the "var" variable is never modified, it has 0 value during all execution, so why can't be the output predictable?
Ok ..I think I understood ...as both threads are running the output can be 00 11 22 for instance ...now I understand why the output cannot be predictable, but I still don't understand what role has the var variable in this?
It is used only for initialize the counter variable...
you're right, that var is always 0.
so it has got no impact on the outcome in fact.
the issue is 2 threads, running together, with no synchronization, each outputting the counter values in order. so the output of the values is indetermined because of that, because you have no guarantee when and for how long each thread runs.
if gun() was synchronized, then there would be a predefined order.
to make synchronization work, you would have to make the method static and then synchronize, or create a specific synchronization block in the function and lock on the var object (which is also static).