Consider a Java class A as follows, where f is a Integer field of A, and u is a local Integer variable of the method foo() in class A.
class A{
int f;
void foo(){
int u;
...
f = 7;
u = f;
...
}
....
}
Is it wrong to claim that:
variable ‘u’ MUST be 7 at the end of “f=7; u =f;”?
My opinion is that ‘f’ may be changed by other threads, so the claim above should be false in general. Am I right?
Thanks for your ideas.
Yes execution could be interrupted between f=7, u=f. You call this a critical area which could be secured using locks, mutexes or semaphores. This way you make sure that no other thread (or even hardware interrupt, well not in java ;)) changes your data without definately wanting it.
In a multi threaded environmend an other Object from a class in the same package as class A could access the Attribute f (because it is not private) and change f to an other value e.g. 5. This Step could be executed between the two statements f = 7; and u = f;. So f could be changed befor assigning to it u. This means you are right.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With