feat[cache]: async lazyGet for SingleCache

This commit is contained in:
godotg
2025-02-23 18:30:23 +08:00
parent 0d1a5cc696
commit 14e4e55b63
2 changed files with 22 additions and 0 deletions
@@ -187,4 +187,11 @@ public abstract class SchedulerBus {
registerScheduler(SchedulerDefinition.valueOf(cron, runnable));
}
/**
* 立刻执行的任务
*/
public static void execute(Runnable runnable) {
executor.execute(ThreadUtils.safeRunnable(runnable));
}
}
@@ -13,6 +13,9 @@
package com.zfoo.scheduler.util;
import com.zfoo.scheduler.manager.SchedulerBus;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.Supplier;
@@ -60,6 +63,18 @@ public class SingleCache<V> {
return cache;
}
public V lazyGet() {
var now = TimeUtils.now();
var refreshTime = refreshTimeAtomic.get();
// 使用双重检测锁的方式
if (now > refreshTime) {
if (refreshTimeAtomic.compareAndSet(refreshTime, now + refreshDuration)) {
SchedulerBus.execute(() -> cache = supplier.get());
}
}
return cache;
}
public void set(V value) {
cache = value;
}