From 34abb0688722c725998916cf5b61d7660c24e0c4 Mon Sep 17 00:00:00 2001 From: Gil Tene Date: Wed, 30 Mar 2016 17:04:09 +0200 Subject: [PATCH] 8147844: new method j.l.Thread.onSpinWait() and the corresponding x86 hotspot instrinsic See JEP-285 for details Co-authored-by: Ivan Krylov Reviewed-by: psandoz, alanb, dholmes --- .../share/classes/java/lang/Thread.java | 39 +++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/jdk/src/java.base/share/classes/java/lang/Thread.java b/jdk/src/java.base/share/classes/java/lang/Thread.java index eb47a05427d..972815e16c7 100644 --- a/jdk/src/java.base/share/classes/java/lang/Thread.java +++ b/jdk/src/java.base/share/classes/java/lang/Thread.java @@ -340,6 +340,45 @@ class Thread implements Runnable { sleep(millis); } + /** + * Indicates that the caller is momentarily unable to progress, until the + * occurrence of one or more actions on the part of other activities. By + * invoking this method within each iteration of a spin-wait loop construct, + * the calling thread indicates to the runtime that it is busy-waiting. + * The runtime may take action to improve the performance of invoking + * spin-wait loop constructions. + *

+ * @apiNote + * As an example consider a method in a class that spins in a loop until + * some flag is set outside of that method. A call to the {@code onSpinWait} + * method should be placed inside the spin loop. + *

{@code
+     *     class EventHandler {
+     *         volatile boolean eventNotificationNotReceived;
+     *         void waitForEventAndHandleIt() {
+     *             while ( eventNotificationNotReceived ) {
+     *                 java.lang.Thread.onSpinWait();
+     *             }
+     *             readAndProcessEvent();
+     *         }
+     *
+     *         void readAndProcessEvent() {
+     *             // Read event from some source and process it
+     *              . . .
+     *         }
+     *     }
+     * }
+ *

+ * The code above would remain correct even if the {@code onSpinWait} + * method was not called at all. However on some architectures the Java + * Virtual Machine may issue the processor instructions to address such + * code patterns in a more beneficial way. + *

+ * @since 9 + */ + @HotSpotIntrinsicCandidate + public static void onSpinWait() {} + /** * Initializes a Thread with the current AccessControlContext. * @see #init(ThreadGroup,Runnable,String,long,AccessControlContext,boolean)