java - Multiple locks - Behind the scene -
class { 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() { (int = 0; < 1000000; i++) { insert1(); insert2(); } } above part of code, here thread t1 calls firing() , t2 calls firing(). used lock1 , lock2 both thread not wait release lock . question happens behind scene ?
lock1 , lock2 object members of class a.
is there relation between lock1 , lock2 list1.add(5), list2.add(5), members of lock1 , lock2 object ? or used insted of ?.
when used synchronized void insert1() , synchronized void insert2() or synchronized(this), void insert1() , void insert2() members of class , lock of class acquired ,this happens behind scenes in above case 2 object created acquire different lock.
what if have many methods void insert1() needed synchronized should create many locks = new object(); ?
synchronized(lock1) 1 thing, , one thing only: prevents other threads synchronizing on same object @ same time. that's all.
here's how , why use it:
you have object (e.g., list1) has kind of state, , wish update object (i.e., change state) calling method list1.add(...). problem synchronized solves is, method list1.add() may have put object temporary, invalid state in order effect update. don't want thread able look @ state of list1 while other thread updating it.
so, designate lock object (e.g., lock1 in example). , make sure every block of code in program either updates list1 or looks at list1 inside synchronized(lock1){ ... } block.
since no 2 threads can synchronize on same object @ same time, no 2 threads able modify or use list1 @ same time.
Comments
Post a Comment