Search code examples
javamultithreadingreentrantlock

ReentrantLock fairness parameter


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:

  1. thread scheduler wakes up t1 thread (who is not the longest waiting thread)
  2. t1 tries to acquire the lock
  3. lock rejects t1 because t1 is not the longest waiting thread
  4. t1 goes to sleep
  5. thread scheduler wakes up a thread

Does 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).


Solution

  • 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.