D
Daniel
Hi,
After perusing the newsgroups for a good while I have read a number of
disturbing things about the keyword volatile. Among the worst of these
is a statement by "concurrency expert" Bill Pugh that "some JVMs
completely ignore volatile". See:
http://www.cs.umd.edu/~pugh/java/memoryModel/JavaOneBOF/BOF-6up.pdf
However I am not looking for any complex functionality out of volatile
such as atomic operations on long/double variables, etc. I just want
to know if it's generally safe to use volatile in threads in the
following way (on possibly any Java 1.1+ JVM):
class MyThread extends Thread
{
private volatile boolean running = true;
public void stopMe()
{
running = false;
}
public void run()
{
while (running)
{
// Do something useful
}
}
}
I would like to think this always works, because it is very similar to
the method Sun has for stopping a thread on their tutorial. Now I know
Sun's documentation isn't always the most accurate, but for something
as important as ending a thread, you'd like to hope they got it right.
If I can't rely on volatile in this case, what other options do I
have? Syncrhonize ALL access to the variable "running"? This seems
quite inefficient to me, especially if the loop in the run() method
must execute many times very fast.
I'd appreciate any thoughts on the matter. Thanks,
Daniel
After perusing the newsgroups for a good while I have read a number of
disturbing things about the keyword volatile. Among the worst of these
is a statement by "concurrency expert" Bill Pugh that "some JVMs
completely ignore volatile". See:
http://www.cs.umd.edu/~pugh/java/memoryModel/JavaOneBOF/BOF-6up.pdf
However I am not looking for any complex functionality out of volatile
such as atomic operations on long/double variables, etc. I just want
to know if it's generally safe to use volatile in threads in the
following way (on possibly any Java 1.1+ JVM):
class MyThread extends Thread
{
private volatile boolean running = true;
public void stopMe()
{
running = false;
}
public void run()
{
while (running)
{
// Do something useful
}
}
}
I would like to think this always works, because it is very similar to
the method Sun has for stopping a thread on their tutorial. Now I know
Sun's documentation isn't always the most accurate, but for something
as important as ending a thread, you'd like to hope they got it right.
If I can't rely on volatile in this case, what other options do I
have? Syncrhonize ALL access to the variable "running"? This seems
quite inefficient to me, especially if the loop in the run() method
must execute many times very fast.
I'd appreciate any thoughts on the matter. Thanks,
Daniel