英文:
Updating fields only if file was modified
问题
我有一个包含一些配置数据的 JSON 文件。解析工作正常,但我正在尝试实现配置的实时更新。因此,我设置了一个定时器,每隔几秒钟执行该任务,而且一切都运行良好。然而,如果自从最新解析以来未对配置进行修改,我希望避免再次解析文件带来的开销。
我编写了以下代码来实现这一点,然而,尽管执行了this.timestamp = latestTimestamp;
,但字段变量 timestamp
仍然保持为零,而 latestTimestamp
则保持着最新的时间戳。我很困惑,因为这对我来说毫无意义。我在这里漏掉了什么?
@NonNull private String configFilePath;
@Getter private JSONObject configuration;
private long timestamp = 0;
/**
* 更新字段
* @throws IOException 如果在打开/读取文件时发生错误
* @throws ParseException 如果解析 JSON 文件时发生错误
*/
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;
// 即使再次调用时文件未被修改,上述条件也会导致 `false`
// 因为 `this.timestamp` 在某种程度上仍然保持为 0
}
上述代码是一个简化版本。完整的类可以在这里找到。
英文:
I have a JSON file containing some configuration data. Parsing it works all well, but I am trying to achieve a live update of the configuration. Thus, I set a scheduler to do the task every few seconds, and it works all well either. However, if no modification was made to the configuration since the latest parsing, I want to avoid the overhead of parsing the file once again.
I have written the following code to achieve that, however the field variable timestamp
remains at zero despite this.timestamp = latestTimestamp;
is executed while latestTimestamp
holds the latest timestamp. I am confused now as it makes absolutely no sense to me. What am I missing here?
@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
}
The above code is a simplified version. The complete Class can be found here.
答案1
得分: 1
所以我认为 ""the field variable timestamp remains at zero" 只有在您的调度程序创建了一个新对象 JSONUpdater
的情况下才可能发生,这会将 timestamp
变量再次重置为0。尝试将其设置为 Singleton
。
英文:
So I think "the field variable timestamp remains at zero" is only possible if your scheduler is creating a new object of your class JSONUpdater
, which resets the timestamp
variable to 0 again. Try making it Singleton
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论