chenhao-db commented on code in PR #53761:
URL: https://github.com/apache/spark/pull/53761#discussion_r2702765242


##########
core/src/main/java/org/apache/spark/util/BestEffortLazyVal.java:
##########
@@ -38,24 +41,37 @@
  *   
href="https://docs.scala-lang.org/scala3/reference/changed-features/lazy-vals-init.html";>Lazy
  *   Vals Initialization</a> for more details.
  */
-private[spark] class BestEffortLazyVal[T <: AnyRef](
-    @volatile private[this] var compute: () => T) extends Serializable {
+public class BestEffortLazyVal<T> implements Serializable {
+    private volatile Function0<T> compute;
+    protected volatile T cached;
 
-  private[this] val cached: AtomicReference[T] = new 
AtomicReference(null.asInstanceOf[T])
+    private static final VarHandle HANDLE;
+    static {
+        try {
+            HANDLE = MethodHandles.lookup()
+                .in(BestEffortLazyVal.class)
+                .findVarHandle(BestEffortLazyVal.class, "cached", 
Object.class);
+        } catch (ReflectiveOperationException e) {
+            throw new IllegalStateException("Failed to initialize VarHandle", 
e);
+        }
+    }
+
+    public BestEffortLazyVal(Function0<T> compute) {
+        this.compute = compute;
+    }
 
-  def apply(): T = {
-    val value = cached.get()
-    if (value != null) {
-      value
-    } else {
-      val f = compute
-      if (f != null) {
-        val newValue = f()
-        assert(newValue != null, "compute function cannot return null.")
-        cached.compareAndSet(null.asInstanceOf[T], newValue)
-        compute = null  // allow closure to be GC'd
-      }
-      cached.get()
+    public T apply() {
+        T value = cached;
+        if (value != null) {
+            return value;
+        }
+        Function0<T> f = compute;
+        if (f != null) {
+            T newValue = f.apply();
+            assert newValue != null: "compute function cannot return null.";
+            HANDLE.compareAndSet(this, null, newValue);
+            compute = null; // allow closure to be GC'd
+        }
+        return cached;

Review Comment:
   From the doc of 
https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/lang/invoke/VarHandle.html#getVolatile(java.lang.Object...):
   
   > Returns the value of a variable, with memory semantics of reading as if 
the variable was declared volatile.
   
   So I think it is not necessay, because the `cached` field is already 
declared volatile.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to