Reading a few threads (common concurrency problems, volatile keyword, memory model) I\'m confused about concurrency issues in Java.
I have a lot of fields that are acces
If you have to ask, use locks. volatile
can be useful in some cases, but it's very, very difficult to get right. For example:
class Foo {
private volatile int counter = 0;
int Increment() {
counter++;
return counter;
}
}
If two threads run Increment()
at the same time, it's possible for the result to be counter = 1
. This is because the computer will first retrieve counter
, add one, then save it back. Volatile just forces the save and load to occur in a specific order relative to other statements.
Note that synchronized
usually obviates the need for volatile
- if all accesses to a given field are protected by the same monitor, volatile
will never be needed.
Using volatile
to make lockless algorithms is very, very difficult; stick to synchronized
unless you have hard evidence that it's too slow already, and have done detailed analysis on the algorithm you plan to implement.