aspose file tools
The moose likes Java in General and the fly likes Which thread will get the lock Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Java » Java in General
Reply 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: 102


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: 1148
    
    3

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: 16680
    
  19

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: 32599
    
    4
Hope I’m not too late, but welcome to the Ranch
Diplav Srivastava
Greenhorn

Joined: Aug 17, 2011
Posts: 3

Thanks Ritchie
 
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to run our stuff on 16 servers instead of 3.
 
subject: Which thread will get the lock
 
Similar Threads
Synchronization & Locks.
Monitor - Multi Threading
synchronization understanding
URLyBird 1.3.1: Locking Problem
Please explain synchronization logic in this example