From a437ef75b98c7cd58e82ebb8406f4d10b6c09f51 Mon Sep 17 00:00:00 2001 From: mariofusco Date: Fri, 12 Jul 2024 11:59:39 +0200 Subject: [PATCH] make LazyFaultTolerance lock-free --- .../core/apiimpl/LazyFaultTolerance.java | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/implementation/core/src/main/java/io/smallrye/faulttolerance/core/apiimpl/LazyFaultTolerance.java b/implementation/core/src/main/java/io/smallrye/faulttolerance/core/apiimpl/LazyFaultTolerance.java index 69b90066..32a6f7f6 100644 --- a/implementation/core/src/main/java/io/smallrye/faulttolerance/core/apiimpl/LazyFaultTolerance.java +++ b/implementation/core/src/main/java/io/smallrye/faulttolerance/core/apiimpl/LazyFaultTolerance.java @@ -1,6 +1,7 @@ package io.smallrye.faulttolerance.core.apiimpl; import java.util.concurrent.Callable; +import java.util.concurrent.atomic.AtomicReference; import java.util.function.Supplier; import io.smallrye.faulttolerance.api.FaultTolerance; @@ -9,7 +10,7 @@ public final class LazyFaultTolerance implements FaultTolerance { private final Supplier> builder; private final Class asyncType; - private volatile FaultTolerance instance; + private final AtomicReference> instance = new AtomicReference<>(null); LazyFaultTolerance(Supplier> builder, Class asyncType) { this.builder = builder; @@ -36,15 +37,13 @@ public void run(Runnable action) { } private FaultTolerance instance() { - FaultTolerance instance = this.instance; + FaultTolerance instance = this.instance.get(); if (instance == null) { - synchronized (this) { - instance = this.instance; - if (instance == null) { - instance = builder.get(); - this.instance = instance; - } + instance = builder.get(); + if (this.instance.compareAndSet(null, instance)) { + return instance; } + instance = this.instance.get(); } return instance; }