Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

About the semantics of a simple Java program

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.

like image 300
zell Avatar asked Jun 24 '26 11:06

zell


2 Answers

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.

like image 198
clambake Avatar answered Jun 26 '26 00:06

clambake


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.

like image 27
Simulant Avatar answered Jun 25 '26 23:06

Simulant



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!