Suppose there is a counter which is incremented by several threads. Are the following implementations equivalent?
Implementation 1 (Use volatile modifier only):
class Test1 {
private volatile int counter;
...
void increment() {
counter ++;
}
}
Implementation 2 (Volatile modifier is not used, instead the synchronized block is used):
class Test2 {
private int counter;
...
void increment() {
synchronized(this) {
counter ++;
}
}
}