mirror of
https://gitee.com/dromara/hutool.git
synced 2026-02-09 09:16:26 +08:00
fix issue IDFMXJ,对stopWatch类中的stop方法计算出的耗时做 “非负校验”,确保耗时不会为负数。
This commit is contained in:
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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());
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user