0

Let say i have following code

int i =0;
setvalue(int i){this.i = i}
getvalue(){return i}

Now 200 thread calling setValue with random[a...b] number.
And 200 thread calling getValue

Now what all values will be seen by thread calling getValue:

  1. Is it possible to see a value which is not in [a...b] set?
  2. Is it guaranteed to see values only in set [a...b]? If yes some underlying info will be helpfull.
  3. Behaviour is not defined by jvm?
  4. Will the behaviour changes for long/ double/ String/ referenceToAObject?

EDIT: I am interested in referenceToAObject , that is if instead of int i, we have Object i in above sample, So basic question is reference updation atomic in nature ?

Bhuvan
  • 4,028
  • 6
  • 42
  • 84
  • 2
    For primitive `int`, no thread should ever see any intermediate value. But, without synchronization, it is possible that some thread might get starved, and only see certain values. `long` and `double` are _not_ guaranteed to be atomic. – Tim Biegeleisen May 14 '19 at 05:00
  • @TimBiegeleisen what about referenceToObject – Bhuvan May 14 '19 at 05:30
  • 1
    A reference is always an atomic value, i.e. will never appear to point to a wrong or illegal memory location, however, this does not apply to the object’s fields. For immutable objects like `String`, there is a guaranty that you will always see a fully constructed object, but for other objects, accessing it without proper synchronization can lead to an inconsistent state. You can see, reading or writing a reference is an atomic operation, but accessing the object behind it, is already a different operation. – Holger May 14 '19 at 11:46

0 Answers0