-2

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.

2
  • 2
    "// 10000" Note that the correct result is 10001, because you used <=10000. Commented May 20, 2021 at 11:54
  • @AndyTurner, yes, you're right. The answer should be 10001 Commented May 20, 2021 at 12:36

1 Answer 1

2

You're not waiting for all the threads to complete. executor.shutdown() just stops executor accepting new work.

You need to use executor.awaitTermination(...) after executor.shutdown();.

Ideone demo

Also, you should surround the read of demoClass.count with a lock/unlock pair, in order to establish the happens-before relationship between the writes to the variable in the thread and the read.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.