aspose file tools*
The moose likes Threads and Synchronization and the fly likes doubt in Syncronized blocks Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "doubt in Syncronized blocks" Watch "doubt in Syncronized blocks" New topic
Author

doubt in Syncronized blocks

ravindra patil
Ranch Hand

Joined: Sep 01, 2006
Posts: 229
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

Joined: Mar 07, 2010
Posts: 17
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

Joined: Jan 09, 2008
Posts: 525
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 ... ...


BEE MBA PMP SCJP-6
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: doubt in Syncronized blocks