wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Synchronization & Locks. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Synchronization & Locks." Watch "Synchronization & Locks." New topic
Author

Synchronization & Locks.

Shah Chunky
Ranch Hand

Joined: Dec 27, 2000
Posts: 116
Hello all...
I read this article on Threads:-
Q.1) What is critical section?
Ans:- Only one thread can enter that section of code.
Q.2) Is code section in synchronized method can be considered as critical section?
Ans: (a) Only code section in static synchronized method can be considered as critical section, since the Class object is locked. Two threads can never enter that code section at the same time.
(b) Code block in instance synchronized method is not critical section. Since one instance of object is locked, but other thread still can enter the same section of code through different instance of object.
What i don't understand is how come in Ans.2 (b) it says "...but other thread still can enter the same section of code through different instance of object."
Does'nt it mean that if a thread enters a Sync instance method it acquires lock
on current object :-
E.x:- synchronized void met()
is equal to :- void met()
{
synchronized(this);
}
So if current object is locked how come other thread can enter this method.
Can someone Explain me where m i wrong ?
Thanks


Shah Chunky - Sun Certified Java2 Programmer.
sajida kal
Ranch Hand

Joined: Mar 22, 2001
Posts: 89
Hi,
I changed your code a bit to try to explain this to you. It is a pretty contrived example, so bear with me!

Both threads have their instance of a assigned to two different objects or two different instances. So the code in synchronized met can be run by both threads at once since they are NOT sharing the same object. That is why .. if current object is locked how come other thread can enter this method.(since the other thread has another instance altogether).
Of course if u assigned instance variable a in both t and t1 to the same object, then this would not be true. So either one thread or both can execute when an instance method is synchronized depending on the object they access.
Whereas if we had a Class level synchronized method A then we are certain that ONLY one thread at a time can execute regardless of how many instances of A were created .
Hope this helps you.
Cheers
Sajida
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Synchronization & Locks.
 
Similar Threads
Syncronized & serializable
Accesing two synchronized methods
Thread Synchronization
locks and monitor
to yield() or not to yield()?