mirror of
https://gitflic.ru/project/openide/openide.git
synced 2025-12-16 14:23:28 +07:00
52 lines
1.3 KiB
HTML
52 lines
1.3 KiB
HTML
<html>
|
|
<body>
|
|
Reports <code>while</code> loops that spin on the
|
|
value of a non-<code>volatile</code> field, waiting for it to be changed by another thread.
|
|
<p>
|
|
In addition to being potentially extremely CPU intensive when little work is done inside the loop, such
|
|
loops are likely to have different semantics from what was intended.
|
|
The Java Memory Model allows such loops to never complete even if another thread changes the field's value.
|
|
</p>
|
|
<p>
|
|
Additionally, since Java 9 it's recommended to call <code>Thread.onSpinWait()</code> inside a spin loop
|
|
on a <code>volatile</code> field, which may significantly improve performance on some hardware.
|
|
</p>
|
|
<p><b>Example:</b></p>
|
|
<pre><code>
|
|
class SpinsOnField {
|
|
boolean ready = false;
|
|
|
|
void run() {
|
|
while (!ready) {
|
|
}
|
|
// do some work
|
|
}
|
|
|
|
void markAsReady() {
|
|
ready = true;
|
|
}
|
|
}
|
|
</code></pre>
|
|
<p>After the quick-fix is applied:</p>
|
|
<pre><code>
|
|
class SpinsOnField {
|
|
volatile boolean ready = false;
|
|
|
|
void run() {
|
|
while (!ready) {
|
|
Thread.onSpinWait();
|
|
}
|
|
// do some work
|
|
}
|
|
|
|
void markAsReady() {
|
|
ready = true;
|
|
}
|
|
}
|
|
</code></pre>
|
|
<!-- tooltip end -->
|
|
<p>
|
|
Use the inspection options to only report empty <code>while</code> loops.
|
|
<p>
|
|
</body>
|
|
</html> |