🔄 Busy spin (or busy waiting) is a low-level concurrency technique where a thread actively waits for a condition to become true by looping continuously, instead of using traditional blocking mechanisms like wait()
, sleep()
, or park()
.
🔄 What is Busy Spinning?
A busy spin loop looks like this:
while (!condition) {
// do nothing (just spin)
}
The thread burns CPU cycles checking the condition repeatedly without releasing the CPU.
✅ When Would You Ever Want That?
Busy spinning is used in high-performance, low-latency systems where the cost of:
- Blocking and context switching (via
wait()
/sleep()
/park()
) - Is higher than just wasting some CPU cycles.
It trades CPU usage for latency — a micro-optimization in real-time or ultra-fast systems.
🧠 Example Use Case:
- Low-latency trading apps
- High-throughput message queues (like Disruptor library)
- Polling a hardware signal (in some embedded systems)
- Spinlocks in CPUs
⚠️ Why It’s Dangerous in Most Apps
Problem | Why It Happens |
---|---|
🔥 CPU usage | The thread never yields or sleeps |
🧵 Starvation | Other threads may not get CPU time |
😓 Battery drain | Especially bad on mobile or low-power systems |
❌ Not scalable | Doesn’t work well when many threads spin |
✅ Safer Version: Yield in the Loop
while (!condition) {
Thread.yield(); // hint to scheduler: "I'm not doing work, let others go"
}
Or:
while (!condition) {
LockSupport.parkNanos(1); // sleep for a few nanoseconds
}
📘 When to Use Busy Spin?
Only when:
- You’re doing something extremely time-sensitive
- You know blocking would introduce unacceptable latency
- You’re working in custom concurrency code (like writing your own queue or lock)
🧠 Summary
Feature | Busy Spin |
---|---|
CPU usage | 🔥 High |
Latency | 🟢 Low (reacts quickly) |
Thread context switch | ❌ Avoided |
Use case | 🧬 High-performance, low-latency |
General recommendation | ⚠️ Avoid unless you know what you’re doing |