I'm a newbie in java programming and I know that Multithreading is not a trivial topic in Java, also I working as C developer for almost 3 years.
I've read this topic: "Multiple locks - Behind the scene" and I understand it totally but I've one concern.
I update the code as follow:
package multithreading;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Worker {
private List<Integer> list1 = new ArrayList<Integer>();
private List<Integer> list2 = new ArrayList<Integer>();
private Object lock1 = new Object();
private Object lock2 = new Object();
private void updateList1(int i) {
synchronized (lock1) {
try {
Thread.sleep(1);
} catch (InterruptedException ex) {
Logger.getLogger(Worker.class.getName()).log(Level.SEVERE, null, ex);
}
list1.add(1);
}
}
private void updateList2(int i) {
synchronized (lock2) {
try {
Thread.sleep(1);
} catch (InterruptedException ex) {
Logger.getLogger(Worker.class.getName()).log(Level.SEVERE, null, ex);
}
list2.add(1);
}
}
public void process(int ii) {
for (int i = 0; i < 1000; i++) {
updateList1(ii);
updateList2(ii);
}
}
public void execute() {
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
process(1);
}
});
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
process(2);
}
});
long start = System.currentTimeMillis();
t1.start();
t2.start();
try {
t1.join();
t2.join();
} catch (InterruptedException ex) {
Logger.getLogger(Worker.class.getName()).log(Level.SEVERE, null, ex);
}
long end = System.currentTimeMillis();
System.out.println("Time taken: " + (end - start));
System.out.println("List1: " + list1.size() + "; list2: " + list2.size());
}
}
And in the main class I created an object and called the execute method the output is:
Time taken: 2186
List1: 2000; list2: 2000
However if I made both functions (updateList1, updateList2) are synchronized and removed the synchronized block on lock1 and lock2
the main will output:
Time taken: 4342
List1: 2000; list2: 2000
The concern is the code inside execute() calls updateList1() then updateList2() so it is a sequential calling for both methods, in the first code (using synchronized block) if one thread acquired the lock1 and the other thread trying to call updateList1() it will be waiting for the lock1 to be released by the other thread. So the time must be equivalent in both ways of implementation.
Please calrify the answer and sorry if I understand anything wrongly in Java because this scenario is what I know from my experience in C.