import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import java.io.;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.;
import java.util.concurrent.*;
public class AutoSaveLoad {
private static final String CHECKPOINT_DIR = "path_to_save_checkpoint";
private static final long SAVE_INTERVAL_MINUTES = 10;
private static final String CHECKPOINT_FILE_NAME = "checkpoint.json";
// 主线程中不断更新的Map变量
private static final Map<String, String> dataMap = new ConcurrentHashMap<>();
private static final ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
public static void main(String[] args) {
// 尝试加载最新的检查点
loadLatestCheckpoint();
// 启动定时保存任务
scheduleSave();
// 模拟主线程中对data_map的更新
updateDataPeriodically();
}
private static void saveCheckpoint() {
File dir = new File(CHECKPOINT_DIR);
if (!dir.exists()) {
dir.mkdirs();
}
File checkpointFile = new File(dir, CHECKPOINT_FILE_NAME);
try (Writer writer = Files.newBufferedWriter(Paths.get(checkpointFile.getAbsolutePath()))) {
JSON.writeJSONString(writer, dataMap);
System.out.println("Checkpoint saved at: " + new Date());
} catch (IOException e) {
e.printStackTrace();
}
}
private static void loadLatestCheckpoint() {
File checkpointFile = new File(CHECKPOINT_DIR, CHECKPOINT_FILE_NAME);
if (checkpointFile.exists()) {
try (Reader reader = Files.newBufferedReader(Paths.get(checkpointFile.getAbsolutePath()))) {
dataMap.putAll(JSON.parseObject(reader, new TypeReference<Map<String, String>>() {}));
System.out.println("Loaded checkpoint from: " + checkpointFile.getAbsolutePath());
} catch (IOException e) {
e.printStackTrace();
}
} else {
System.out.println("No checkpoints found.");
}
}
private static void scheduleSave() {
// 定时每SAVE_INTERVAL_MINUTES分钟保存一次检查点
Runnable saveTask = AutoSaveLoad::saveCheckpoint;
scheduler.scheduleAtFixedRate(saveTask, SAVE_INTERVAL_MINUTES, SAVE_INTERVAL_MINUTES, TimeUnit.MINUTES);
}
private static void updateDataPeriodically() {
// 模拟主线程中对dataMap的更新,这里简单地每隔5秒更新一次
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
updateData("dynamic_key", "dynamic_value_" + new Date().getTime());
}
}, 0, 5000); // 每5秒更新一次
}
private static synchronized void updateData(String key, String value) {
dataMap.put(key, value);
System.out.println("Updated dataMap: " + dataMap);
}
// 确保在程序退出时关闭调度器
public static void shutdown() {
if (!scheduler.isShutdown()) {
scheduler.shutdown();
}
}
static {
// 注册关闭钩子以确保程序正常退出时调用shutdown方法
Runtime.getRuntime().addShutdownHook(new Thread(AutoSaveLoad::shutdown));
}
}