gpt4 book ai didi

java - 更新当前时间日期而不在内存中爆炸

转载 作者:行者123 更新时间:2023-12-01 22:51:17 25 4
gpt4 key购买 nike

我编写了以下 Java 代码:

Calendar now = Calendar.getInstance();
now.setTime(new Date());
Date currentDate = null;

while (now.compareTo(stop) < 0 ) {
currentDate = new Date();
now.setTime(currentDate);
}

这意味着在其他组件(特别是:Twitter Streaming 监听器)执行其他操作时跟踪时间流逝。因此,这并不意味着是一个简单的 sleep ,因为其他组件正在同时运行:这个循环只是为了让机器保持占用一段时间,直到 stop 指示的日期到来。

但是,这样做后内存大小会不断增加。我分析了这个东西,发现它在内存中生成了大量的 Date 对象。

有更聪明的方法吗?

提前谢谢您。

最佳答案

最小的更改是使用 setTimeInMillis使用System.currentTimeMillis而不是 setTime:

while (now.compareTo(stop) < 0 ) {                  // Ugh, busy wait, see below
now.setTimeInMillis(System.currentTimeMillis());
}

...或者实际上,首先使用毫秒:

long stopAt = stop.getTimeMillis();
while (System.currentTimeMillis() < stopAt) { // Ugh, busy wait, see below
}

但是,在更广泛的背景下,肯定有一种方法可以完全避免忙等待。忙碌等待几乎从不合适。

So, this is not meant to be a simple sleep, since other components are running in the meanwhile: this loop is just meant to keep the machine occupied for a while, until the date indicated by stop arrives.

可能这些组件正在其他线程上运行,因为您的 while 循环处于忙等待状态。

既然如此,这个线程应该 hibernate ——要么 hibernate 一段时间,要么直到被其他东西唤醒。

例如,您还没有说明 stop 是什么,但当您将它与 compareTo 一起使用时,它可能是一个 Calendar。因此应该可以获得 stopnow 之间的差异(以毫秒为单位,通过 getTimeInMillis ),以及 sleep 。而不是忙着等待:

Calendar now = Calendar.getInstance(); // Initializes to "now", no need to do that yourself
long delay = stop.getTimeInMillis() - now.getTimeInMillis();
if (delay > 0) {
Thread.sleep(delay);
}

关于java - 更新当前时间日期而不在内存中爆炸,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24698500/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com