When I want to update with either synchronized keyword or lock, it works when the sum variable is int but not when it is an Integer object.
code looks like this -
public class TestSynchronized {
private Integer sum = new Integer(0);
public static void main(String[] args) {
TestSynchronized test = new TestSynchronized();
System.out.println("The sum is :" + test.sum);
}
public TestSynchronized() {
ExecutorService executor = Executors.newFixedThreadPool(1000);
for (int i = 0; i <=2000; i++) {
executor.execute(new SumTask());
}
executor.shutdown();
while(!executor.isTerminated()) {
}
}
class SumTask implements Runnable {
Lock lock = new ReentrantLock();
public void run() {
lock.lock();
int value = sum.intValue() + 1;
sum = new Integer(value);
lock.unlock(); // Release the lock
}
}
}