【发布时间】:2020-05-30 15:02:04
【问题描述】:
我有一个包含一些配置数据的 JSON 文件。解析它工作得很好,但我正在尝试实现配置的实时更新。因此,我设置了一个调度程序每隔几秒钟执行一次任务,它也运行良好。但是,如果自上次解析后未对配置进行任何修改,我想避免再次解析文件的开销。
我编写了以下代码来实现这一点,但是尽管在 latestTimestamp 保存最新时间戳时执行了 this.timestamp = latestTimestamp;,但字段变量 timestamp 仍然为零。我现在很困惑,因为这对我来说完全没有意义。我在这里错过了什么?
@NonNull private String configFilePath;
@Getter private JSONObject configuration;
private long timestamp = 0;
/**
* update the fields
* @throws IOException if an error occurred while opening / reading the file
* @throws ParseException if an error occurred parsing the JSON file
*/
public void update() throws IOException, ParseException {
long latestTimestamp = getLatestTimestamp(this.configFilePath);
if (this.timestamp == latestTimestamp)
return;
this.configuration = this.parse(this.configFilePath);
this.timestamp = latestTimestamp;
// the above condition results in `false` when called again despite file is not modified
// because this.timestamp somehow remains 0
}
以上代码为简化版。完整的 Class 可以在here找到。
【问题讨论】:
-
所以我认为“字段变量时间戳保持为零”只有在您的调度程序正在创建您的类 JSONUpdater 的新对象时才可能,这会将时间戳变量再次重置为 0。尝试使其成为单例。还有为什么你的类上没有 Service、Bean 或任何类型的 Component 注释?
-
我一开始是用 MD5 摘要来比较的。当它不起作用时,开始分成多个单独的课程,几乎像健美操一样。但是谢谢,这是有道理的,这意味着:在继续之前,我有很多东西要先重构。
-
那是你问题的根本原因还是你还在搞清楚。
-
抱歉我的回复晚了。是的,这确实是问题所在。有时候,有些问题实在是太简单了,甚至想都不敢想哈哈
-
乐于助人。我会将其添加为答案,以便其他人可以轻松找到此解决方案。请接受并投票赞成答案,以获得更好的效果。