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

Add isMemoized() method to MemoizingSupplier #7469

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
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
48 changes: 46 additions & 2 deletions guava/src/com/google/common/base/Suppliers.java
Original file line number Diff line number Diff line change
Expand Up @@ -154,11 +154,53 @@ public T get() {
return uncheckedCastNullableTToT(value);
}

/**
* Returns whether the value has been memoized without triggering memoization.
*/
public boolean isMemoized() {
return initialized;
}

/**
* Resets the memoized value, allowing the supplier to recompute its value.
* This can be useful in cases where the value needs to be refreshed.
*/
public void reset() {
synchronized (lock) {
initialized = false;
value = null;
}
}

/**
* Returns the memoized value if it has been initialized, otherwise returns {@code null}.
* This method does not trigger memoization.
*/
@CheckForNull
public T getIfMemoized() {
return initialized ? value : null;
}

/**
* Attempts to refresh the memoized value by recomputing it. This method forces recomputation
* even if the value was previously memoized, and it can be used to ensure the value is up to date.
* The recomputation occurs only if the current thread successfully acquires the lock.
*/
public void refresh() {
synchronized (lock) {
T oldValue = value;
value = delegate.get();
initialized = true;
if (!value.equals(oldValue)) {
System.out.println("Memoized value has been refreshed from " + oldValue + " to " + value);
}
}
}
@Override
public String toString() {
return "Suppliers.memoize("
+ (initialized ? "<supplier that returned " + value + ">" : delegate)
+ ")";
+ (initialized ? "<supplier that returned " + value + ">" : delegate)
+ ")";
}

@GwtIncompatible // serialization
Expand All @@ -171,6 +213,8 @@ private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundE
private static final long serialVersionUID = 0;
}



@VisibleForTesting
static class NonSerializableMemoizingSupplier<T extends @Nullable Object> implements Supplier<T> {
private final Object lock = new Object();
Expand Down