You are tuning a real-time data processing application that reads sensor data from a queue. The system must process each sensor reading, but occasionally a reading is invalid (null) and should be skipped. The loop must run indefinitely until the application is shut down gracefully. The current implementation uses a while(true) loop with a break condition when a shutdown flag is set. However, the loop is consuming excessive CPU because it continuously polls the queue even when no data is available. You need to modify the loop to reduce CPU usage while still processing data efficiently. Which approach should you take?
Trap 1: Change the while(true) loop to a for loop that iterates a fixed…
Fixed iteration does not allow infinite processing.
Trap 2: Add a Thread.sleep(100) inside the loop to reduce polling frequency.
Sleep introduces latency and may not eliminate busy-waiting.
Trap 3: Use a do-while loop with a Thread.yield() call to give other…
yield() may not reduce CPU usage significantly.
- A
Change the while(true) loop to a for loop that iterates a fixed number of times.
Why wrong: Fixed iteration does not allow infinite processing.
- B
Replace the polling mechanism with a blocking queue that blocks until data is available.
Blocking queue blocks the thread, reducing CPU usage.
- C
Add a Thread.sleep(100) inside the loop to reduce polling frequency.
Why wrong: Sleep introduces latency and may not eliminate busy-waiting.
- D
Use a do-while loop with a Thread.yield() call to give other threads CPU time.
Why wrong: yield() may not reduce CPU usage significantly.