Forums Register Login

thread and synchronized method

+Pie Number of slices to send: Send
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...
+Pie Number of slices to send: Send
 

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.
+Pie Number of slices to send: Send
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.
Tell me how it all turns out. Here is a tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com


reply
reply
This thread has been viewed 645 times.
Similar Threads
Synchronized blocks
cann someone validate my locking approach?
Does accessing an Object from a synchronized method lock the Object?
locks and monitor
Accessing Synchronized methods in a single object
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 29, 2024 07:33:46.