Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

doubt in Syncronized blocks

 
ravindra patil
Ranch Hand
Posts: 234
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ya , we use syncronized block if we wnat tp protect criticle region it also limits the scope so
if i have method having syncronized block
public void useSyncBlock{

int i=10;
synchonized(this)
{

doCritcalOpreation();

}

system.out.ptintln("out ")

}

so the code inside of sync block is proteted but what about the code outside of the block can multiple threads can acceess it evn though they dont hold object lock
 
Sujeet Kumar Jaiswal
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
public void useSyncBlock{

int i=10; --- 1
synchonized(this) --- 2
{

doCritcalOpreation(); ---3

}

system.out.ptintln("out ") --- 4

}


Code outside the synchronized block: label 1 & 4.

When one of the thread is already inside the synchronized block ' label 3' (has acquired the lock of this object), then all other threads will be able to run till 'label 1' and get blocked for the object lock once they reach 'label 2' (Running State -> Blocked State) and hecne they won't be able to run 'label 4'.
 
Jim Hoglund
Ranch Hand
Posts: 525
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Synchronization does not prevent multiple threads from running a method at the
same time. Rather, it grants an object lock to just one thread giving it exclusive
access to the object - not the code. Other threads are free to run the same code.

Consider many instances of a class and many identical threads. Separate threads
can be simultaneously working through the same synchronized method, each holding
a lock on a different object. The JVM is constantly swapping out the running thread.

Jim ... ...
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic