Moved to core-java-function module
Added concurrent tests
This commit is contained in:
+16
@@ -0,0 +1,16 @@
|
||||
package com.baeldung.lazylambda;
|
||||
|
||||
import java.util.function.Supplier;
|
||||
|
||||
public class LambdaSupplier<T> {
|
||||
|
||||
protected final Supplier<T> expensiveData;
|
||||
|
||||
public LambdaSupplier(Supplier<T> expensiveData) {
|
||||
this.expensiveData = expensiveData;
|
||||
}
|
||||
|
||||
public T getData() {
|
||||
return expensiveData.get();
|
||||
}
|
||||
}
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
package com.baeldung.lazylambda;
|
||||
|
||||
import java.util.function.Supplier;
|
||||
|
||||
public class LazyLambdaSupplier<T> extends LambdaSupplier<T> {
|
||||
|
||||
private T data;
|
||||
|
||||
public LazyLambdaSupplier(Supplier<T> expensiveData) {
|
||||
super(expensiveData);
|
||||
}
|
||||
|
||||
@Override
|
||||
public T getData() {
|
||||
if (data != null) {
|
||||
return data;
|
||||
}
|
||||
return data = expensiveData.get();
|
||||
}
|
||||
|
||||
}
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
package com.baeldung.lazylambda;
|
||||
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
public class LazyLambdaThreadSafeSupplier<T> extends LambdaSupplier<T> {
|
||||
|
||||
private final AtomicReference<T> data;
|
||||
|
||||
public LazyLambdaThreadSafeSupplier(Supplier<T> expensiveData) {
|
||||
super(expensiveData);
|
||||
data = new AtomicReference<>();
|
||||
}
|
||||
|
||||
public T getData() {
|
||||
if (data.get() == null) {
|
||||
synchronized (data) {
|
||||
if (data.get() == null) {
|
||||
data.set(expensiveData.get());
|
||||
}
|
||||
}
|
||||
}
|
||||
return data.get();
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user