I am trying to write lock and sync code and compare their performance difference.
the code:
public abstract class Task { public abstract int getTotal(); } // Lock test class public class TaskWithLock extends Task implements Runnable { private static int total = 0; private final Lock lock = new ReentrantLock(); public void run() { try { lock.lock(); doSomething(); } finally { lock.unlock(); } } private void doSomething() { total++; } public int getTotal() { return total; } } // Synchronized test class public class TaskWithSync extends Task implements Runnable { private static int total = 0; public void run() { synchronized ("") { doSomething(); } } private void doSomething() { total++; } public int getTotal() { return total; } } // Test class public class Test { public static void main(String[] args) throws Exception { int count = 100000; runTasks(TaskWithLock.class, count); runTasks(TaskWithSync.class, count); } public static void runTasks(Class<? extends Runnable> clazz, int count) throws Exception { List<Thread> list = new ArrayList<Thread>(count); for (int i = 0; i < count; i++) { list.add(new Thread(clazz.newInstance())); } for (int i = 0; i < count; i++) { list.get(i).start(); } for (int i = 0; i < count; i++) { list.get(i).join(); } System.out.println(clazz.getSimpleName() + "Total Result: " + ((Task) clazz.newInstance()).getTotal()); } }
I understand that the above lock and the synchronized code block must be the same effect, but the result that I run is not the same, the synchronized code is right, it is always 100000, but the lock code is always incorrect, sometimes 99995 or 99997 or another result but itβs not 100,000.
Console:
TaskWithLock Result: 99991
TaskWithSync Result: 100000
I think my code should have some error, or I understand that Lock is wrong, or Lock cannot be used like this.
Please indicate what might be wrong.
source share