public class Test {
private static int count = 0;
private static final Object lock= new Object();
public synchronized void foo() {
count++;
}
}
Though at first it looks thread safe but it is not as the counter is a static field and to provide atomicity we need to hold a lock on the class object. So there 4 ways of doing it
1) To make the method static
public static synchronized void incrementCount() {
count++;
}
2) To take lock on the Class object explicitly
public void incrementCount() {
synchronize (Test.class) {
count++;
}
}
3) To take a lock on another static Object
private static final Object countLock = new Object();
public void incrementCount() {
synchronize (countLock) {
count++;
}
}
4) Use the new AtomicInteger object from the java.util.concurrent.atomic package
private final static AtomicInteger count = new AtomicInteger(0);
public void foo() {
count.incrementAndGet();
}
No comments:
Post a Comment