aspose file tools
The moose likes Threads and Synchronization and the fly likes volatile scope question Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Java » Threads and Synchronization
Reply 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: 16483
    
    2

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: 2782
    
    2
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://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to run our stuff on 16 servers instead of 3.
 
subject: volatile scope question
 
Similar Threads
class loader
Possible Memory Leak ?
garbage collection
Simple Object Question
trouble setting a Boolean parameter