This article is supposed to be an up-to-date source of curated information about changes that arrived in Java recently and those that are about to…
Leave a CommentMonth: March 2020
Thread#onSpinWait is an interesting JDK9 addition to the Thread API, which is used as a hint that we’re inside a spin-wait loop.
The method itself is… empty:
@HotSpotIntrinsicCandidate public static void onSpinWait() {}
But it can be intrinsified to utilize, for example, x86’s PAUSE instruction – it’s a small thing but results in reduced power consumption and improved performance of spin-wait loops:
Improves the performance of spin-wait loops. When executing a “spin-wait loop,” a Pentium 4 or Intel Xeon processor suffers a severe performance penalty when exiting the loop because it detects a possible memory order violation. The PAUSE instruction provides a hint to the processor that the code sequence is a spin-wait loop. The processor uses this hint to avoid the memory order violation in most situations, which greatly improves processor performance. For this reason, it is recommended that a PAUSE instruction be placed in all spin-wait loops.
Unfortunately, it was introduced only in JDK9, and many libraries need to maintain JDK8(or even JDK6) compatibility.
However, since it’s just a void-returning method, what if we prepared a fallback for it when running on an earlier version of Java when it can’t really be used?
Leave a Comment