I am trying to synchronize 2 threads using Java Concurrent's lock API. The code basically increments a counter to a certain number using 2 threads but the result i am getting is less than the said number even after using locks. Code-
import java.util.concurrent.*; import java.util.concurrent.locks.ReentrantLock; class DemoClass { public int count =0; public ReentrantLock lock = new ReentrantLock(); public void increment() { lock.lock(); try { count++; } finally { lock.unlock(); } } } public class Main { public static void main(String[] args) { ExecutorService executor = Executors.newFixedThreadPool(2); DemoClass demoClass = new DemoClass(); int i=0; for(;i<=10000;i++) { executor.submit(demoClass::increment); } executor.shutdown(); System.out.println( demoClass.count); // 10000 } } Not sure what is it i am doing wrong here.
<=10000.