Skip to content

Commit

Permalink
feat: add RuntimeExpiringMemoizingSupplier
Browse files Browse the repository at this point in the history
  • Loading branch information
pipinet committed Nov 24, 2023
1 parent 0b132b3 commit 8e3f8d3
Show file tree
Hide file tree
Showing 2 changed files with 70 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
package com.qwlabs.lang;

import com.google.common.base.Supplier;

import javax.annotation.CheckForNull;

public class RuntimeExpiringMemoizingSupplier<T> implements Supplier<T> {
private final Supplier<WithExpiring<T>> delegate;
@CheckForNull
private transient volatile T value;
private transient volatile long expirationNanos;

public RuntimeExpiringMemoizingSupplier(Supplier<WithExpiring<T>> delegate) {
this.delegate = delegate;
}

@Override
public T get() {
if (expirationNanos == 0) {
synchronized (this) {
if (expirationNanos == 0) {
realLoad();
}
}
}
long now = System.nanoTime();
if (now > expirationNanos) {
return this.value;
}
synchronized (this) {
realLoad();
}
return value;
}

private void realLoad() {
try {
var withExpiring = delegate.get();
this.value = withExpiring.getData();
this.expirationNanos = System.nanoTime() + withExpiring.getExpiresInNanos();
} catch (Exception e) {
this.value = null;
this.expirationNanos = 0;
}
}
}
24 changes: 24 additions & 0 deletions lang/src/main/java/com/qwlabs/lang/WithExpiring.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package com.qwlabs.lang;

import lombok.Getter;

import java.util.concurrent.TimeUnit;

@Getter
public class WithExpiring<T> {
private final T data;
private final long expiresInNanos;

private WithExpiring(T data, long expiresInNanos) {
this.data = data;
this.expiresInNanos = expiresInNanos;
}

public static <T> WithExpiring<T> of(T data, long expiresIn, TimeUnit timeUnit) {
return new WithExpiring<>(data, timeUnit.toNanos(expiresIn));
}

public static <T> WithExpiring<T> of(T data, long expiresInNanos) {
return new WithExpiring<>(data, expiresInNanos);
}
}

0 comments on commit 8e3f8d3

Please sign in to comment.