Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

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

 
ashwin bhawsar
Ranch Hand
Posts: 62
Eclipse IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 62
Eclipse IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
So you mean non-sync methods will run even if there is lock on that instance ?
 
Balasubramanian Bhaskaran
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, exactly
 
Ram Narayan.M
Ranch Hand
Posts: 247
Chrome Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
ashwin bhawsar
Ranch Hand
Posts: 62
Eclipse IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a lot for you time.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic