All 15 Concurrency & Threads questions
More in Concurrency & Threads
Advertisement
Java › Concurrency & Threads

What is thread starvation, and how can thread priority misuse or unfair lock scheduling contribute to it?

Intermediate

Answer

Thread starvation occurs when a thread is perpetually denied access to a resource it needs to make progress, typically because other threads are repeatedly favored for scheduling or lock acquisition -- setting overly aggressive thread priorities (Thread.setPriority()) can starve lower-priority threads on some JVM/OS combinations (though thread priority is only a hint and behaves inconsistently across platforms, making it generally an unreliable and discouraged tool), and a non-fair lock (the default for both synchronized and ReentrantLock unless fairness is explicitly requested) can theoretically let some threads repeatedly "jump the queue" ahead of a thread that's been waiting longest, though non-fair locks are still generally preferred for their better overall throughput despite this theoretical starvation risk in adversarial scenarios.
// Non-fair (default) ReentrantLock -- higher throughput, but theoretically allows starvation
ReentrantLock lock = new ReentrantLock();  // fair = false by default

// Fair lock -- reduces (but doesn't eliminate) starvation risk, at the cost of some throughput
ReentrantLock fairLock = new ReentrantLock(true);
Real-world example A background task perpetually failing to acquire a heavily-contended lock under sustained load from many higher-frequency competing threads is diagnosed as a starvation issue, addressed by switching that specific lock to fair mode, trading a modest amount of overall throughput for a guarantee that no single thread gets perpetually starved.

Common follow-ups: Why is Thread priority considered an unreliable mechanism across different JVM/OS combinations?;What's the throughput cost of enabling fairness on a ReentrantLock, and when is that trade-off worthwhile?