Java discussion forum to accompany the Javamex web site.

Hi folks, In the article about stopping a thread, it was said that a stop variable needs to be volitile.

I can see that if the variable is public and other threads can alter it directly.  But is this still true if the stop variable is private and encapsulation is used to set it?

Views: 149

Reply to This

Replies to This Discussion

Yes. The need for volatile is because the variable is being modified by different threads: on the one hand, the thread that is being stopped, and on the other, any thread that wants to tell it to stop.

Encapsulation doesn't change that. Whether you set the variable directly or indirectly set it through a method, that doesn't change which thread the variable is being set in.

Thanks Neil

I think the penny has dropped. 

The problem is that two different other threads may want to change it at the same time.

Would I still need the volatile if the thread was only ever started and stopped by the same thread? Perhaps not, but I guess it would be good practice to get in the habit?

PS Your explanation of the three ways to stop a thread was really helpful. 

Second penny dropped and feel the need to correct my own last post!

Even though I may only have one instantiaton of a thread type object, its  run method will be running in a different thread to the method being accessed.

Hence all variables that may be accessed directly or indirectly by another thread must be marked as volatile.

Hope this helps someone else get there head round this tricky subject.

Reply to Discussion


© 2020   Created by Neil Coffey.   Powered by

Badges  |  Report an Issue  |  Terms of Service