• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Can you still access an unsnychronized method even when there is a lock on the object?

 
Joe Lemmer
Ranch Hand
Posts: 171
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi there,

In K&B, Ch.9, page 736, it says:

If a class has both synchronized and non-synchronized methods, multiple threads can still access the class's non-synchronized methods!


I wasn't sure whether that meant that you can still access the unsynchronized methods even if another thread has the object's lock. I wrote the following code to find out:



The out put I get is:



I'm taking this to mean that:
1. The Thread called 'one' starts the run method and enters the synchronized block where it aquires the lock to the LockTest instance.
2. It executes the for loop until i == 100 and then sleeps. *But it still has the lock*
3. Because the Thread one is sleeping, and dispite the fact that Thread one has the lock, the 'main' thread can still access the *unsynchronized* printStuff() method of the LockThis instance, so it is allowed to execute the for loop in the main method.
4. Thread one wakes up and finishes executing the run() method and releases the lock on the LockTest object.

Does everyone else agree that this is what is happening?

Cheers

Joe
 
Peter Taucher
Ranch Hand
Posts: 174
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sure, but your example lacks synchronized methods. Your synchronization is on block-level, I'm not sure why you don't declare the run method as synchronized. Of course, I don't think it would change anything ; - )

 
Sahil Kapoor
Ranch Hand
Posts: 316
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes , i think you are absolutely right !!!

Locks scenario comes only when a particular thread has to run a synchorized method on a particular object, otherwise in case of non-synchronized method ,thread dnt care for locks on the objects !!!

Cheers!!!
 
Joe Lemmer
Ranch Hand
Posts: 171
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I synchronized a block rather than a method for no other reason than... just because. And I need to learn the syntax. I'm not sure how synchronized blocks are used in practice, but as the lock was still on the 'this' object it doesn't make a difference to what I wanted to find out.

Thanks for your replies, I appreciate it.

Cheers

Joe

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic