• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

thread and synchronized method

 
Juni Panda
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can any one please clear me on this doubt,

If there are two threads running and there are two methods, one is synchronized and the other is not..
first thread is accessing the non synchronized method (which is a lengthy one) of the object and it's on it's half way and suddenly the second thread comes to access the synchronized method of that object.. which means it's going to lock the object..
Now in this scenario what happens..... two threads are accessing two different methods but when the object is locked by the second thread, what will happen to the first thread and the method it was processing...
 
Paul Clapham
Sheriff
Pie
Posts: 20978
31
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Juni Panda wrote:which means it's going to lock the object


No, it doesn't mean that at all. There is no such thing as locking an object. What it means is, the second thread is going to acquire the object's monitor (because it entered the synchronized block).

Other threads which don't attempt to acquire the same object's monitor (like the first thread in your example) are completely unaffected by this action and continue to run.
 
Jeff Verdegan
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Any thread can execute any unsynchronized method at any time.

There's no such thing as "locking an object". The only thing the synchronized keyword does for mutual exclusion is to obtain a lock and (waiting first if some other thread already holds it) and prevent other threads from obtaining that lock. By using synchronization, you can only prevent other threads from executing code that syncs on the same lock. It's a cooperative paradigm.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic