Skip to content

Commit 1803215

Browse files
stsypanovleventov
authored andcommitted
Add advice for busy-wait loops
1 parent 394d926 commit 1803215

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

README.md

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -145,6 +145,7 @@ Threads and Executors
145145
- the future is completed and the callback is attached from the same thread pool?
146146
- [Adding a callback to a `CompletableFuture` (`SettableFuture`) in non-async mode is justified?
147147
](#cf-beware-non-async)
148+
- [Is `Thread.sleep()` usage in spin-wait loop justified?](#thread-sleep)
148149

149150
Parallel Streams
150151
- [Parallel Stream computation takes more than 100us in total?](#justify-parallel-stream-use)
@@ -1170,6 +1171,37 @@ See also the Javadoc for [`ListenableFuture.addListener()`](
11701171
https://guava.dev/releases/28.1-jre/api/docs/com/google/common/util/concurrent/ListenableFuture.html#addListener-java.lang.Runnable-java.util.concurrent.Executor-
11711172
) describing this problem.
11721173

1174+
<a name="thread-sleep"></a>
1175+
[#](#thread-sleep) TE.8. Developers often use busy-wait pattern like
1176+
```java
1177+
class EventHandler {
1178+
volatile boolean eventNotificationNotReceived;
1179+
1180+
void waitForEventAndHandleIt() {
1181+
while (eventNotificationNotReceived) {
1182+
Thread.sleep(TimeUnit.SECONDS.toMillis(1L));
1183+
}
1184+
readAndProcessEvent();
1185+
}
1186+
1187+
void readAndProcessEvent() {
1188+
// Read event from some source and process it
1189+
}
1190+
}
1191+
```
1192+
If there is a busy wait loop, is it explained in a comment why it's needed in the specific case,
1193+
and that the costs and potential problems associated with busy waiting either don't apply in the specific case,
1194+
or are outweighed by the benefits?
1195+
1196+
Pay attention that `Thread.sleep()` **in certain cases** could be replaced with:
1197+
- synchronization primitive (like `Semaphore`)
1198+
- `Object.wait()`/`Object.notify()`
1199+
- `Thread.yield()`
1200+
- `Thread.onSpinWait()`
1201+
1202+
The mentioned pattern is covered by IDEA's inspection "Busy wait" which is currently off by default.
1203+
It will be on by default when [IDEA-226838](https://youtrack.jetbrains.com/issue/IDEA-226838) is fixed.
1204+
11731205
### Parallel Streams
11741206

11751207
<a name="justify-parallel-stream-use"></a>

0 commit comments

Comments
 (0)