英文:
VOLATILE required in single core multi Threaded environment?
问题
我需要使用VOLATILE变量吗,如果我在单核机器上,而且是多线程环境?
根据我的理解,线程没有自己的缓存空间。
它们使用所在核心的缓存。
如果是单核机器,它们将共享相同的缓存。
请纠正/补充我的理解。
英文:
Do I need to use VOLATILE variable, if I am on a single core machine & multi Threaded environment
From my understanding, Threads do not have a cache space of their own.
They use the cache of the core they are running in.
Now if it is a single core machine, they will all be sharing the same cache.
Please correct/addMore over my understanding
答案1
得分: 3
编译器也可以重新排列指令。
例如:
class SomeRunnable implements Runnable {
public boolean stop;
public void run() {
while (!stop)
println("hello");
}
}
由于stop
变量没有标记为volatile
(或者没有在同步块中使用),编译器可以自由地将上述代码转换为:
class SomeRunnable implements Runnable {
public boolean stop;
public void run() {
if (stop) return;
for (;;) {
println("hello");
}
}
}
这种优化称为“循环不变代码移动”。之所以进行这种优化是为了减少读取stop
的开销;如果它在循环中不会改变,那么读取它有什么意义。
最好不要考虑缓存,因为:
- 除非你知道你在谈论什么,否则你可能没有正确理解
- 它取决于CPU架构。
如果你想理解Java并发,那么你需要了解Java内存模型。
英文:
The compiler can also reorder instructions.
For example:
class SomeRunnable implements Runnable{
public boolean stop;
public void run(){
while(!stop)
println("hello");
}
}
Since the stop variable isn't marked as volatile (or used in a synchronized block), the compiler is free to transform the above code to:
class SomeRunnable implements Runnable{
public boolean stop;
public void run(){
if(stop)return;
for(;;)
println("hello");
}
}
This optimization is called 'loop invariant code motion'. The reason this optimization is done is to reduce the overhead of reading 'stop'; what is the point of reading it, if it doesn't change in the loop.
It is best not to think in terms of caches because:
- unless you know what you are talking about, probably you don't understand it correctly
- it depends on the CPU architecture.
If you want to understand Java concurrent, then you need to understand the Java Memory Model.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论