fix issue IDFMXJ,对stopWatch类中的stop方法计算出的耗时做 “非负校验”,确保耗时不会为负数。

This commit is contained in:
shad0wm00n
2025-12-24 21:12:39 +08:00
parent de93fa7670
commit d66610b8a5
2 changed files with 32 additions and 2 deletions

View File

@@ -171,8 +171,9 @@ public class StopWatch {
}
final long lastTime = System.nanoTime() - this.startTimeNanos;
this.totalTimeNanos += lastTime;
this.lastTaskInfo = new TaskInfo(this.currentTaskName, lastTime);
final long safeLastTime = Math.max(0, lastTime);
this.totalTimeNanos += safeLastTime;
this.lastTaskInfo = new TaskInfo(this.currentTaskName, safeLastTime);
if (null != this.taskList) {
this.taskList.add(this.lastTaskInfo);
}

View File

@@ -0,0 +1,29 @@
package cn.hutool.core.date;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import java.lang.reflect.Field;
/**
* StopWatch 异常未释放资源问题测试问题2
*/
public class IssueIDFMXJTest {
@Test
void stopWatchNegativeTimeTest() throws NoSuchFieldException, IllegalAccessException {
final StopWatch stopWatch = new StopWatch();
stopWatch.start("负耗时测试任务");
// 反射修改startTimeNanos为当前时间+1秒模拟nanoTime回退
final Field startTimeNanosField = StopWatch.class.getDeclaredField("startTimeNanos");
startTimeNanosField.setAccessible(true);
startTimeNanosField.set(stopWatch, System.nanoTime() + 1_000_000_000);
stopWatch.stop();
Assertions.assertEquals(0, stopWatch.getLastTaskTimeNanos());
Assertions.assertEquals(0, stopWatch.getTotalTimeNanos());
}
}