1 import jdk.internal.misc.Unsafe;
 2 
 3 class UnsafeStoreReference {
 4   private static final Unsafe U = Unsafe.getUnsafe();
 5   private transient volatile Node head;
 6   private static final long HEAD
 7               = U.objectFieldOffset(UnsafeStoreReference.class, "head");
 8   private transient volatile Node tail;
 9 
10   static class Node {}
11 
12   // inspired from java.util.concurrent.locks.AbstractQueuedSynchronizer::tryInitializeHead
13   void test() {
14     Node h = new Node();
15 
16     if (U.compareAndSetReference(this, HEAD, null, h))
17         tail = h;
18   }
19 
20   public static void main(String[] args) {
21     UnsafeStoreReference kase = new UnsafeStoreReference();
22 
23     for (int i = 0; i < 100_000; i++) {
24         kase.test();
25         if (kase.head != kase.tail) {
26             throw new RuntimeException("wrong result");
27         }
28         kase.head = kase.tail = null;
29     }
30   }
31 }