diff options
author | Valerij Fredriksen <valerij92@gmail.com> | 2021-02-26 19:54:12 +0100 |
---|---|---|
committer | Valerij Fredriksen <valerij92@gmail.com> | 2021-02-26 19:54:12 +0100 |
commit | 2b9a03d6bdbf468015047ee08a37e839b70a3e73 (patch) | |
tree | 625af7213ce74c38b6faa724c6cdcbe912baf327 /vespajlib | |
parent | 1454578133592494bfda4b2a07df51e66d7e03e6 (diff) |
Code review fixes
Diffstat (limited to 'vespajlib')
-rw-r--r-- | vespajlib/src/main/java/com/yahoo/lang/CachedSupplier.java | 19 | ||||
-rw-r--r-- | vespajlib/src/test/java/com/yahoo/lang/CachedSupplierTest.java | 2 |
2 files changed, 12 insertions, 9 deletions
diff --git a/vespajlib/src/main/java/com/yahoo/lang/CachedSupplier.java b/vespajlib/src/main/java/com/yahoo/lang/CachedSupplier.java index 07ce1250855..49b8dbdca8a 100644 --- a/vespajlib/src/main/java/com/yahoo/lang/CachedSupplier.java +++ b/vespajlib/src/main/java/com/yahoo/lang/CachedSupplier.java @@ -7,13 +7,15 @@ import java.time.Instant; import java.util.function.Supplier; /** - * Supplier that caches the value for a given duration with ability to invalidate at demand. + * Supplier that caches the value for a given duration with ability to invalidate on demand. * Is thread safe. * * @author freva */ public class CachedSupplier<T> implements Supplier<T> { + private final Object monitor = new Object(); + private final Supplier<T> delegate; private final Duration period; private final Clock clock; @@ -34,18 +36,19 @@ public class CachedSupplier<T> implements Supplier<T> { @Override public T get() { - synchronized (this) { - if (clock.instant().isAfter(nextRefresh)) - refresh(); + synchronized (monitor) { + if (clock.instant().isAfter(nextRefresh)) { + this.value = delegate.get(); + this.nextRefresh = clock.instant().plus(period); + } } return value; } - public void refresh() { - synchronized (this) { - this.value = delegate.get(); - this.nextRefresh = clock.instant().plus(period); + public void invalidate() { + synchronized (monitor) { + this.nextRefresh = Instant.MIN; } } diff --git a/vespajlib/src/test/java/com/yahoo/lang/CachedSupplierTest.java b/vespajlib/src/test/java/com/yahoo/lang/CachedSupplierTest.java index b0dc1262ebc..342d76b43d6 100644 --- a/vespajlib/src/test/java/com/yahoo/lang/CachedSupplierTest.java +++ b/vespajlib/src/test/java/com/yahoo/lang/CachedSupplierTest.java @@ -29,7 +29,7 @@ public class CachedSupplierTest { assertEquals(2, supplier.get().intValue()); assertEquals(2, supplier.get().intValue()); - supplier.refresh(); + supplier.invalidate(); assertEquals(3, supplier.get().intValue()); assertEquals(3, supplier.get().intValue()); |