M Sach
M Sach

Reputation: 34424

synchronized lock grant order when multiple thread ask for it?

When multiple thread try to acquire the lock on synchronized when lock is already acquired by one thread. My understanding was that lock will be given in order of acquire lock request.

But as per the book O'Reilly Java threads lock will be given that is best for platform. Thats very abstract statement.I think platform mainly meant OS here. My question what is the criteria based on which JVM decides what is best for platform and how developer accounts it while doing programming?

Update:- i know i can use Lock object with fairness argument. But just want to know how does it work with synchronized locks?

Upvotes: 1

Views: 265

Answers (3)

Enno Shioji
Enno Shioji

Reputation: 26882

As of JDK6 (in HotSpot JVMs), it uses an algorithm called biased locking. Have a look at this white paper by Oracle, esp. the section on biased locking. They cite this paper that further describes the details of the algorithm.

As for how the developer should account for this, IMO the only important part is that it's unfair. You prob. never have to worry about anything else unless you are coding a high frequency trading platform or something.

You should generally favor unfair locking against fair locking unless you have a reason, as the former typically has higher throughput.

Upvotes: 0

Ted Bigham
Ted Bigham

Reputation: 4341

My understanding was that lock will be given in order of acquire lock request.

I believe that's only true for green threads (which no one really uses anymore).

My question what is the criteria based on which JVM decides what is best for platform and how developer accounts it while doing programming?

I don't think the JVM "decides" at runtime. The threading model will just be compiled into the JVM.

Upvotes: 0

John Vint
John Vint

Reputation: 40256

synchronized acquisition follows a non-fair lock policy. That is, threads that enter first while blocking may not be the first to acquire. If you want a fair lock use a new ReentrantLock(true)

Upvotes: 2

Related Questions