I was reading on multithreading in Java and using synchronized blocks. Suppose I have two different, independent synchronized blocks. I can have them run in parallel, by using a lock each for both the synchronized blocks. But if I use the same lock for both synchronized blocks, I think only one can run at a given time. Am i wrong to think so? If no, why am I getting the below strange result?
Assume I have two independent operations, increment1 and increment2, called by a different thread each.
public class AppMultipleSynchronization {
private static int counter1 = 0;
private static int counter2 = 0;
private static Object lock1 = new Object();
private static Object lock2 = new Object();
public static void increment1() {
synchronized (lock1) {
counter1++;
}
}
public static void increment2() {
synchronized (lock2) {
counter2++;
}
}
public static void main(String[] args) {
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 100000000; i++) {
increment1();
}
}
});
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 100000000; i++) {
increment2();
}
}
});
long startTime = System.currentTimeMillis();
t1.start();
t2.start();
try {
t1.join();
t2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
long endTime = System.currentTimeMillis();
System.out.println("total time taken: " + (endTime - startTime) + "ms");
System.out.println("counter1: " + counter1 + "\ncounter2: " + counter2);
}
}
As you can see, I am using a different lock for for both increments.
To use the same lock, use the exact same program, replace with lock1
in both cases.
Output in case of two locks:
total time taken: 13437ms
counter1: 100000000
counter2: 100000000
Output in case of single lock:
total time taken: 5139ms
counter1: 100000000
counter2: 100000000