在Java中遇到的最常见的并发问题是什么? [英] What is the most frequent concurrency issue you've encountered in Java?
问题描述
这是Java中常见并发问题的一种轮询。一个例子可能是经典的死锁或竞态条件,或者可能是Swing中的EDT线程错误。我对广泛的可能问题感兴趣,但也在最常见的问题。因此,请留下每个注释的Java并发错误的一个具体答案,如果看到您遇到的错误,请投票。
This is a poll of sorts about common concurrency problems in Java. An example might be the classic deadlock or race condition or perhaps EDT threading bugs in Swing. I'm interested both in a breadth of possible issues but also in what issues are most common. So, please leave one specific answer of a Java concurrency bug per comment and vote up if you see one you've encountered.
推荐答案
我看到的最常见的并发问题是,没有意识到一个线程写入的字段不能保证被另一个线程看到。这是一个常见的应用:
The most common concurrency problem I've seen, is not realizing that a field written by one thread is not guaranteed to be seen by a different thread. A common application of this:
class MyThread extends Thread {
private boolean stop = false;
public void run() {
while(!stop) {
doSomeWork();
}
}
public void setStop() {
this.stop = true;
}
}
只要停止不是或 setStop
和运行不会同步,这不能保证工作。这个错误尤其糟糕,因为在99.999%在实践中没有关系,因为读者线程最终会看到改变 - 但我们不知道他多久看到它。
As long as stop is not volatile or setStop
and run
are not synchronized this is not guaranteed to work. This mistake is especially devilish as in 99.999% it won't matter in practice as the reader thread will eventually see the change - but we don't know how soon he saw it.
这篇关于在Java中遇到的最常见的并发问题是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!