Reputation: 202
This question is full theoretical, I'm sorry but I cannot avoid this time.
I'm learning about ReentrantLock
and read this:
Note however, that fairness of locks does not guarantee fairness of thread scheduling.
What does this mean? How can I imagine this?
Let's suppose that the lock is not held by anyone right now:
t1
thread (who is not the longest waiting thread) t1
tries to acquire the lockt1
because t1
is not the longest waiting threadt1
goes to sleepDoes Java work this way? In a very unsuccesful case this would mean lots of context switching (that leads to poor throughput, that is written down in the documentation).
Upvotes: 3
Views: 2991
Reputation: 122
What does this mean?
This means that a thread holding lock may continue holding the lock as long as it wants and can reacquire the same lock many time in succession and the longest waiting thread will keep waiting until current thread releases the lock.
So, fairness guarantee comes to play only when lock is free and java thread scheduler has to decide which thread the lock should be given to. And it is given to longest waiting thread(in case of synchronized, it's random).
It also means that the thread holding the lock is not being scheduled frequently and other threads are given more CPU time, so this thread is not able to complete and thus not releasing the lock.
Upvotes: 3
Reputation: 533492
What does this mean?
The OS will schedule the thread to run whenever it likes.
How can I imagine this?
The OS has little idea what the JVM would like to run next.
Does Java work this way?
Yes, Java doesn't control the OS scheduler.
Upvotes: 5