Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

make LazyFaultTolerance lock-free #1034

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -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;
Expand All @@ -9,7 +10,7 @@ public final class LazyFaultTolerance<T> implements FaultTolerance<T> {
private final Supplier<FaultTolerance<T>> builder;
private final Class<?> asyncType;

private volatile FaultTolerance<T> instance;
private final AtomicReference<FaultTolerance<T>> instance = new AtomicReference<>(null);

LazyFaultTolerance(Supplier<FaultTolerance<T>> builder, Class<?> asyncType) {
this.builder = builder;
Expand All @@ -36,15 +37,13 @@ public void run(Runnable action) {
}

private FaultTolerance<T> instance() {
FaultTolerance<T> instance = this.instance;
FaultTolerance<T> instance = this.instance.get();
Copy link

@franz1981 franz1981 Jul 12, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this is making builder.get() to be called more than once, changing the expected behaviour for users.
Using ReentrantLock(s) is preferrable here - or use a 2 state lock-free behaviour instead

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;
}
Expand Down