GeeCON Prague 2014*
The moose likes Threads and Synchronization and the fly likes Locking doubt : Thread calling a method on an instance even if another thread has a lock on it. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "Locking doubt : Thread calling a method on an instance even if another thread has a lock on it." Watch "Locking doubt : Thread calling a method on an instance even if another thread has a lock on it." New topic
Author

Locking doubt : Thread calling a method on an instance even if another thread has a lock on it.

ashwin bhawsar
Ranch Hand

Joined: Mar 16, 2011
Posts: 62

Locking concept doubt: Thread calling a method on an instance even if another thread has a lock on that same instance ?

I have a Student class with 2 non-static methods, one synchronized and another non-synchronized method.
I am creating 2 threads (Thread_A & Thread_B) using the same instance of the Student class.
Thread_A will always call the synchronized method and Thread_B will always call the non-synchronized method.

Suppose Thread_A starts before Thread_B and enters the synchronized method. Now Thread_A has acquired a lock on the instance of the Student class and will not realease it untill it finishes the execution. My doubt is that even if the Thread_A has a lock on the student instance, why Thread_B is able to call the Non-Sync method on the same student instance before Thread_A releases the lock on that instance.

Why locking works only if both methods are synchronized.





Output:
Balasubramanian Bhaskaran
Greenhorn

Joined: Jun 08, 2012
Posts: 2
For executing non-synchronized method, lock is not needed. So irrelevant of who owns the lock, the non synchronized method will be executed, and no thread safety is guaranteed on that method.
ashwin bhawsar
Ranch Hand

Joined: Mar 16, 2011
Posts: 62

So you mean non-sync methods will run even if there is lock on that instance ?
Balasubramanian Bhaskaran
Greenhorn

Joined: Jun 08, 2012
Posts: 2
Yes, exactly
Ram Narayan.M
Ranch Hand

Joined: Jul 11, 2010
Posts: 247

Synchronizing is done if the method has some code to access critical common resource which should not be spoiled by multiple thread running on that method concurrently.

Unsynchronized does not deal with that critical common resource so no danger of multiple threads accessing that method concurrently.

So, its legal to allow thread running on Unsynchronized method on an instance even if that instance has been locked by another thread.


SCJP 6 [SCJP - Old is Gold]
ashwin bhawsar
Ranch Hand

Joined: Mar 16, 2011
Posts: 62

Thanks a lot for you time.
 
GeeCON Prague 2014
 
subject: Locking doubt : Thread calling a method on an instance even if another thread has a lock on it.