Skip to content

Commit

Permalink
Create LateInitValue:;computeIfUninitialized
Browse files Browse the repository at this point in the history
  • Loading branch information
Glavo committed May 16, 2024
1 parent 6ae226b commit e4afd57
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 4 deletions.
20 changes: 18 additions & 2 deletions kala-base/src/main/java/kala/value/LateInitValue.java
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,16 @@
*/
package kala.value;

import java.util.function.Supplier;

public final class LateInitValue<T> implements Value<T> {
private volatile boolean initialized = false;
private T value;

public boolean isInitialized() {
return initialized;
}

public void initialize(T value) {
if (initialized) {
throw new IllegalStateException("Value is initialized");
Expand All @@ -32,8 +38,18 @@ public void initialize(T value) {
}
}

public boolean isInitialized() {
return initialized;
public T computeIfUninitialized(Supplier<? extends T> supplier) {
if (initialized) {
return value;
}

synchronized (this) {
if (initialized) {
return value;
}

return value = supplier.get();
}
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,20 @@
*/
package kala.value.primitive;

<#if IsSpecialized || Type == "Boolean">
import java.util.function.${Type}Supplier;
<#else>
import kala.function.${Type}Supplier;
</#if>

public final class LateInit${Type}Value extends Abstract${Type}Value implements ${Type}Value {
private volatile boolean initialized = false;
private ${PrimitiveType} value;

public boolean isInitialized() {
return initialized;
}

public void initialize(${PrimitiveType} value) {
if (initialized) {
throw new IllegalStateException("Value is initialized");
Expand All @@ -32,8 +42,18 @@ public final class LateInit${Type}Value extends Abstract${Type}Value implements
}
}

public boolean isInitialized() {
return initialized;
public ${PrimitiveType} computeIfUninitialized(${Type}Supplier supplier) {
if (initialized) {
return value;
}

synchronized (this) {
if (initialized) {
return value;
}

return value = supplier.getAs${Type}();
}
}

@Override
Expand Down

0 comments on commit e4afd57

Please sign in to comment.