0

Consider below scenario, it says if str is volatile it means any update by any thread accessing str, will directly update on main stack instead of local Thread cache.

class A{
  volatile String str;     
  volatile B b=new B();
}

class B{
  int a;
  C c;
}

For b volatile object, how scenario will work?

I read few links it says only reference is volatile and not the property of object itself, what does that mean, can some one help me with some example as I am finding it little bit difficult to understand.

if reference is synchronized, then how it will help, what is the use of it?

Abimaran Kugathasan
  • 31,165
  • 11
  • 75
  • 105
Jayesh
  • 6,047
  • 13
  • 49
  • 81

1 Answers1

1

First scenario:

  • thread 1 does a.b = new B();
  • then thread 2 does B b = a.b;

In this case, you have the guarantee that the object referenced by b in the second thread is the new B() that the first thread has assigned to the variable.

Second scenario:

  • thread 1 does a.b.setFoo("hello");
  • then thread 2 does String s = a.b.getFoo();

In this case, you have no guarantee regarding the value of s in the second thread. It could be "hello", or it could be a previous value of a.b.foo (unless the foo attribute in class B is itself volatile, or the setters and getters are synchronized).

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • Can `thread 2` read the latest value of `foo` if `thread 1` reassigns the `b` ref ? e.g. `thread 1`: `{ a.b.setFoo("Hello"); a.b = a.b; }` then `thread 2`: `{ a.b.getFoo(); }` – Venkata Raju Oct 08 '17 at 21:24
  • Comments to this [answer](https://stackoverflow.com/a/4614433/1812434) discuss the same point but not clear (to me :) ) – Venkata Raju Oct 08 '17 at 21:42