doubt in Syncronized blocks

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

posted 7 years ago

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

posted 7 years ago

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.