-3

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.

wut
  • 19
  • 4

1 Answers1

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.

Andy Turner
  • 137,514
  • 11
  • 162
  • 243