Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes need synchronize clarification Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "need synchronize clarification" Watch "need synchronize clarification" New topic

need synchronize clarification

Higgledy Smith
Ranch Hand

Joined: Mar 07, 2006
Posts: 192
If a class has a synchronized method and a non-synchnized method.
Two threads running; both operating on 1 instance of the above class.

If thread A gets the lock and is in the synchronized method.
Can thread B access the non-synchronized method while thread A has the lock and is using the synch'd method?

If I had 2 instances of the same class, there would be 2 locks available. 1 for each instance. Is this correct thinking? In other words locks are associated to instances of a class not to the Class.
marc weber

Joined: Aug 31, 2004
Posts: 11343

A synchronized method requires that the executing thread obtain the lock. A non-synchronized method does not require a lock to be obtained. So you are correct: Non-synchronized methods can be accessed while another thread has the lock.

There are 2 types of locks: An object lock (one for each instance) and a class lock. The class lock is needed for accessing synchronized static code. So if you have 2 instances of the same class, then there are 2 distinct object locks, but there is only 1 class lock. Which lock is required depends on whether the synchronized code is static or not.

"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
I agree. Here's the link:
subject: need synchronize clarification
It's not a secret anymore!