Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

volatile scope question

 
Jack Nam
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Everybody,

I have a question on the scope of volatile.

If I have two classes MyObj and MyOtherObj. MyOtherObj is refered by MyObj.

public class MyObj {

public MyOtherObj myOtherObj = new MyOtherObj();

}

public class MyOtherObj {

public Boolean myBoolean= true;

}

And I have another class has a reference to MyObj with volatile attribute. Do I have to declare myBoolean as volatile to make it thread-safe?

public class MyClass{
private volatile MyObj myObj = new MyObj();

// access myBoolean from this class
myObj.myOtherObj.myBoolean = false;

}
 
Paul Clapham
Sheriff
Posts: 21128
32
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No. But that's because declaring a variable as volatile doesn't make it thread-safe.
 
Jack Nam
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Assume that only one thread do the write operation, other just read. Would it be safe from memory visibility point of view?

Sorry for not mentioned that.

Paul Clapham wrote:No. But that's because declaring a variable as volatile doesn't make it thread-safe.
 
Mike Simmons
Ranch Hand
Posts: 3090
14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jack Nam wrote:Assume that only one thread do the write operation, other just read. Would it be safe from memory visibility point of view?

Yes, writing the reference to a volatile field is sufficient to ensure visibility to other threads (including visibility of fields within MyOtherObj.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic