java - Understanding lock scope -


from link, understand "since lock() , unlock() method calls explicit, can move them anywhere, establishing lock scope, single line of code scope spans multiple methods"

so understand above statement is

public class test {     lock l = new reentrantlock();      void mymethod1() {         l.lock();         // stuff here     }      void mymethod2() {         // more stuff here         l.unlock();     } } 

so 1 can call method1 , method2 in sequence , assume call thread safe.

i not sure if it's true said above.

what if calls method2 when executing method1/method2 pair? doesn't complicate things.

i think lock should acquired , released in function itself, before control returned function. understanding correct?

answer first question:

what if calls method2 when executing method1/method2 pair? doesn't complicate things.

suppose thread calls unlock() method on reentrantlock object then illegalmonitorstateexception thrown. because thread not acquiring lock , when tries unlock exception.
it not have effect on execution or locking of first thread acquiring lock.

  • same thread:

    • lock: if same thread acquiring lock again tries acquire lock lock counter increments.
    • unlock: if same thread acquiring lock tries unlock lock counter decrements , lock counter becomes 0, thread releases lock.
  • different thread:

    • lock: if lock held thread current thread becomes disabled thread scheduling purposes , lies dormant until lock has been acquired, @ time lock hold count set one.
    • unlock: if different thread tries unlock when not holding lock illegalmonitorstateexception thrown.

that reason reentrantlock lock , unlock mandates have try-catch or throw mechanism because throws exception.

read below excerpt reentrantlock#unlock()

if current thread holder of lock hold count decremented. if hold count 0 lock released. if current thread not holder of lock {@link illegalmonitorstateexception} thrown.

answer second question:

i think lock should acquired , released in function itself, before control returned function. understanding correct?

that's whole purpose of reentrantlock, can extend locking mechanism other methods, cannot synchronized blocks , methods. see below reentrantlock

a reentrant mutual exclusion lock same basic behavior , semantics implicit monitor lock accessed using synchronized methods , statements, but extended capabilities.


Comments

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

Rendering JButton to get the JCheckBox behavior in a JTable by using images does not update my table -