Skip to content

Commit

Permalink
Add facility to set max age based on time needed for call
Browse files Browse the repository at this point in the history
  • Loading branch information
fhoeben committed Oct 10, 2017
1 parent 3b02a59 commit c69bd10
Showing 1 changed file with 18 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
*/
public class BooleanCache {
private static long maxCacheAge = 500;
private static int ageFactor = 3;

private final BooleanSupplier supplier;
private boolean cachedValue;
Expand All @@ -17,9 +18,16 @@ public BooleanCache(BooleanSupplier supplier) {
}

public boolean getValue() {
if (validUntil < System.currentTimeMillis()) {
long start = System.currentTimeMillis();
if (validUntil < start) {
cachedValue = supplier.getAsBoolean();
validUntil = System.currentTimeMillis() + maxCacheAge;
long end = System.currentTimeMillis();
if (ageFactor > 0) {
long autoAge = (end - start) * ageFactor;
validUntil = end + autoAge;
} else {
validUntil = end + maxCacheAge;
}
}
return cachedValue;
}
Expand All @@ -31,4 +39,12 @@ public static void setMaxCacheAge(long maxCacheAge) {
public static long getMaxCacheAge() {
return maxCacheAge;
}

public static int getAgeFactor() {
return ageFactor;
}

public static void setAgeFactor(int ageFactor) {
BooleanCache.ageFactor = ageFactor;
}
}

0 comments on commit c69bd10

Please sign in to comment.