关于中断Jetty线程返回线程池时中断状态处理的技术问询
Let's tackle your questions one by one—this is a common gotcha when working with Jetty's concurrency model, so it's great you're digging into the details:
1. Does an interrupted Jetty thread have its interrupt state reset before returning to the pool?
By default, no—the interrupt state isn't automatically reset by the task execution logic itself. If a thread gets interrupted mid-task (e.g., via Thread.interrupt()), and your task code doesn't explicitly clear the interrupt flag (like calling Thread.interrupted() or handling InterruptedException properly), the thread will return to the pool with the interrupt flag still set.
2. If the interrupt flag isn't cleared, is there a cleanup mechanism in place?
Absolutely. Jetty's core thread pool implementation (QueuedThreadPool) has a built-in cleanup mechanism controlled by the clearInterrupt configuration option (which defaults to true).
When a thread finishes its task and is about to be returned to the pool:
- If
clearInterruptis enabled (the default), Jetty callsThread.interrupted()on the thread. This method both returns the current interrupt state and resets the flag to false. - You can disable this behavior by calling
QueuedThreadPool.setClearInterrupt(false), but this is rarely recommended—leaving the interrupt flag set can cause unexpected behavior in future tasks (like breaking blocking operations that respond to interrupts, such asThread.sleep()orObject.wait()).
3. Are there measures to ensure no threads in the pool have an active interrupt state?
With Jetty's default configuration, yes—the platform takes active steps to keep pool threads in a clean state:
- The
clearInterruptmechanism mentioned above is the primary safeguard. It ensures threads are stripped of their interrupt flags before being added back to the pool. - Even in edge cases (e.g., a custom task manually re-sets the interrupt flag before finishing), the pool's thread reclamation process will catch it and clear the flag (again, assuming
clearInterruptis enabled). - When a thread is pulled from the pool to run a new task, the pool's internal logic also ensures the thread is in a usable state—so you don't have to worry about inheriting an interrupted state from a previous task.
In short: Jetty handles interrupt state cleanup out of the box. You only need to worry about this if you've modified the clearInterrupt setting or are writing tasks that intentionally manipulate interrupt flags in non-standard ways.
内容的提问来源于stack exchange,提问作者Jessica.A

