自动保存档

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));
}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值