File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Threads and Synchronization and the fly likes thread and synchronized method Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "thread and synchronized method" Watch "thread and synchronized method" New topic

thread and synchronized method

Juni Panda

Joined: Mar 18, 2012
Posts: 5
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

Joined: Oct 14, 2005
Posts: 19973

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

Joined: Jan 03, 2004
Posts: 6109

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.
I agree. Here's the link:
subject: thread and synchronized method
jQuery in Action, 3rd edition