mirror of
https://github.com/tiennm99/zfoo.git
synced 2026-08-09 14:22:40 +00:00
feat[cache]: async lazyGet for SingleCache
This commit is contained in:
@@ -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;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user