Reputation: 164
class A {
Object lock1 = new Object();
Object lock2 = new Object();
List<Integer> list1 = new ArrayList<>();
List<Integer> list2 = new ArrayList<>();
void insert1() {
synchronized (lock1) {
list1.add(5);
}
}
void insert2() {
synchronized (lock2) {
list2.add(5);
}
}
void firing() {
for (int i = 0; i < 1000000; i++) {
insert1();
insert2();
}
}
Above is an part of code, here thread t1 calls firing() and t2 calls firing(). I used lock1 and lock2 so that both thread will not wait to release the lock . My question is what happens behind the scene ?
lock1 and lock2 object are members of class A.
Is there any relation between lock1 and lock2 with list1.add(5), list2.add(5), Are they also members of lock1 and lock2 Object ? or It is just used insted of this ?.
When used synchronized void insert1() and synchronized void insert2() or synchronized(this), void insert1() and void insert2() are members of class A and lock of class A is acquired ,this happens behind the scenes but in above case two object are created just to acquire different lock.
What if I have many methods like void insert1() which are also needed to be synchronized than should I create that many locks = new Object(); ?
Upvotes: 0
Views: 162
Reputation: 27210
synchronized(lock1)
Does one thing, and one thing only: It prevents other threads from synchronizing on the same object at the same time. That's all.
Here's how and why you use it:
You have an object (e.g., list1
) that has some kind of state, and you wish to update the object (i.e., change its state) by calling a method like list1.add(...)
. The problem that synchronized
solves is, a method like list1.add()
may have to put the object into a temporary, invalid state in order to effect the update. You don't want any thread to be able to look at the state of list1 while some other thread is updating it.
So, you designate a lock object (e.g., lock1
in your example). And you make sure that every block of code in your program that either updates list1
or even looks at list1
does it inside a synchronized(lock1){ ... }
block.
Since no two threads can synchronize on the same object at the same time, no two threads will be able to modify or use list1
at the same time.
Upvotes: 1