*
The moose likes Java in General and the fly likes Which thread will get the lock Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Which thread will get the lock" Watch "Which thread will get the lock" New topic
Author

Which thread will get the lock

Arka Sharma
Ranch Hand

Joined: Jun 15, 2011
Posts: 103


Hi,

Let's consider a scenario. A thread is running the code blocks inside a synchronized method thus owns the lock of that object.now let say two other thread simultaneously try to get the lock but waits since there is already one thread is having it.Now the thread is done with the critical section and releases the lock.Which one of the two waiting thread will enter the critical section when both of the waiting thread is of same priority value.

Regards,
Arka
Tony Docherty
Bartender

Joined: Aug 07, 2007
Posts: 2163
    
  47
Either of them.
AFAIK at the end of a synchronized block all threads waiting on that block are woken and (assuming they are all the same priority) whichever one acquires the monitor gets to execute the code.
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18500
    
  40

Tony Docherty wrote:Either of them.
AFAIK at the end of a synchronized block all threads waiting on that block are woken and (assuming they are all the same priority) whichever one acquires the monitor gets to execute the code.


Agreed. And they don't even have to be at the same priority. Thread priority behaviors are handle by the underlying threading system (for most JVM implementations), and there are a few reasons why the OS threading system may choose to run a lower priority thread over a higher priority thread.

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Diplav Srivastava
Greenhorn

Joined: Aug 17, 2011
Posts: 3

The two thread will be waiting for acquiring the lock.sinc both of them have equal priority so anyone of them can acquire.here is a point.if the priority is differet by a small value 1 then even in that case jvm does not ensure that the higher priority thrrad will run
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 37897
    
  22
Hope I’m not too late, but welcome to the Ranch
Diplav Srivastava
Greenhorn

Joined: Aug 17, 2011
Posts: 3

Thanks Ritchie
 
Don't get me started about those stupid light bulbs.
 
subject: Which thread will get the lock
 
Similar Threads
URLyBird 1.3.1: Locking Problem
Synchronization & Locks.
synchronization understanding
Monitor - Multi Threading
Please explain synchronization logic in this example