@@ -145,6 +145,7 @@ Threads and Executors
145
145
- the future is completed and the callback is attached from the same thread pool?
146
146
- [ Adding a callback to a ` CompletableFuture ` (` SettableFuture ` ) in non-async mode is justified?
147
147
] ( #cf-beware-non-async )
148
+ - [ Is ` Thread.sleep() ` usage in spin-wait loop justified?] ( #thread-sleep )
148
149
149
150
Parallel Streams
150
151
- [ Parallel Stream computation takes more than 100us in total?] ( #justify-parallel-stream-use )
@@ -1170,6 +1171,37 @@ See also the Javadoc for [`ListenableFuture.addListener()`](
1170
1171
https://guava.dev/releases/28.1-jre/api/docs/com/google/common/util/concurrent/ListenableFuture.html#addListener-java.lang.Runnable-java.util.concurrent.Executor-
1171
1172
) describing this problem.
1172
1173
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
+
1173
1205
### Parallel Streams
1174
1206
1175
1207
<a name =" justify-parallel-stream-use " ></a >
0 commit comments