I am just trying to understand... Will I achieve the same result using the below two approaches? I mostly see the first approach only. Is there anything wrong with the second approach? We can use AtomicInteger to achieve the same but just wanted to know. Can someone please clarify?
Approach#1
public class Counter {
private int counter = 0;
public int getCount() {
synchronized(this) {
return counter;
}
}
public void increment() {
synchronized(this) {
counter++;
}
}
}
Approach#2
public class Counter {
private volatile int counter = 0;
public int getCount() {
return counter;
}
public synchronized void increment() {
counter++;
}
}