aspose file tools*
The moose likes Threads and Synchronization and the fly likes volatile scope question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "volatile scope question" Watch "volatile scope question" New topic
Author

volatile scope question

Jack Nam
Ranch Hand

Joined: Feb 09, 2010
Posts: 33
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
Bartender

Joined: Oct 14, 2005
Posts: 18882
    
    8

No. But that's because declaring a variable as volatile doesn't make it thread-safe.
Jack Nam
Ranch Hand

Joined: Feb 09, 2010
Posts: 33
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

Joined: Mar 05, 2008
Posts: 3018
    
  10
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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: volatile scope question