Multithreading multiple locks seem slower than single lock Multithreading multiple locks seem slower than single lock multithreading multithreading

Multithreading multiple locks seem slower than single lock


am i wrong to think so? if no, why am i getting the below strange result?

No you are not wrong. If you are using 2 locks then 2 threads can be executing the 2 different blocks at the same time.

What you are seeing is most likely because these sorts of fine grained, threaded, performance tests are very subtle. This may have much more to do about branch and lock prediction than about true runtime. The JVM makes guesses about whether a lock should be tested in a spin loop versus a true mutex wait/queue. It can dramatically optimize this code given that the actual work is just ++. It may also be that t1.start() starts and runs so fast that it finishes before the t2.start() can be executed.

If you change the lock body to be more substantial, you should start to see that the 2 locks will result in faster wall clock runtime. For example, if you do a loop of ++ operations in the block:

public static void increment1() {    synchronized (lock1) {        for (int i = 0; i < 100000000; i++) {            counter1++;        }    }}...public void run() {    for (int i = 0; i < 10000; i++) {        increment1();    }}

Then with 1 locks I get:

total time taken: 62822mscounter1: -727379968counter2: -727379968

but 2 locks gets:

total time taken: 30902mscounter1: -727379968counter2: -727379968

Lastly, the JVM does a whole bunch of class loading, gcc -O3 equivalence, and machine code inlining during the first seconds and even minutes of runtime. Anytime you are trying to run Java performance tests, you need to make sure your program is running for a long time to get some level of accurate numbers.