I am trying to follow the ReentrantLock Example in Java, Difference between synchronized vs ReentrantLock kind of tutorial. And I have a demo started with -ea
on as
public class ReentrantLockZero {
private static ReentrantLock CountLock = new ReentrantLock();
private static int count = 0;
private static final int RESULT_COUNT = 10_000;
public static void main(String... args) throws Exception {
ThreadPoolExecutor threadPoolExecutor = getMyCachedThreadPool();
for (int i = 0; i < RESULT_COUNT; ++i) {
threadPoolExecutor.submit(ReentrantLockZero::getCount);
threadPoolExecutor.submit(ReentrantLockZero::getCountUsingLock);
}
threadPoolExecutor.shutdown();
threadPoolExecutor.awaitTermination(10, TimeUnit.SECONDS);
assert count == RESULT_COUNT * 2;
}
private static synchronized int getCount() {
count++;
System.out.println(Thread.currentThread().getName() + " counting in synchronized: " + count);
return count;
}
private static int getCountUsingLock() {
CountLock.lock();
try {
count++;
System.out.println(Thread.currentThread().getName() + " counting in lock: " + count);
return count;
} finally {
CountLock.unlock();
}
}
}
When using ReentrantLock
as the second method getCountUsingLock
, I will get java.lang.AssertionError
but when I commented them out to use synchronized
, it would be okay.
Considering its ReentrantLock, I removed the CountLock
defined in the class and using local lock as following, but it still not work.
private static int getCountUsingLock() {
ReentrantLock countLock = new ReentrantLock();
countLock.lock();
try {
count++;
System.out.println(Thread.currentThread().getName() + " counting in lock: " + count);
return count;
} finally {
countLock.unlock();
}
}
What's the missed point here?
Any help will be appreciated ;)