Avoid Calling Thread.interrupted()

ID

java.thread_interrupted_static_vs_instance

Severity

low

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Reliability

Language

Java

Tags

concurrency, reliability

Description

Reports calls to Thread.interrupted(). This static method tests and clears the interrupt status of the current thread, which is almost always surprising behavior.

Rationale

Thread.interrupted() is a static method. Calling it as Thread.interrupted() or even someThread.interrupted() always operates on the current thread, not on the referenced instance. Worse, it has the side effect of clearing the interrupt flag. Developers almost always intend to use the instance method isInterrupted(), which queries the flag without clearing it.

// Bad -- clears the interrupt flag of the current thread
boolean b = Thread.interrupted();

Remediation

Use Thread.currentThread().isInterrupted() to query the current thread’s interrupt status without clearing it, or use someThread.isInterrupted() for a specific thread:

// Good -- queries without clearing
boolean b = Thread.currentThread().isInterrupted();
boolean b2 = worker.isInterrupted();