From d66610b8a5c94d8e666273c8e1fc1f91aa82417c Mon Sep 17 00:00:00 2001 From: shad0wm00n Date: Wed, 24 Dec 2025 21:12:39 +0800 Subject: [PATCH] =?UTF-8?q?fix=20issue=20IDFMXJ=EF=BC=8C=E5=AF=B9stopWatch?= =?UTF-8?q?=E7=B1=BB=E4=B8=AD=E7=9A=84stop=E6=96=B9=E6=B3=95=E8=AE=A1?= =?UTF-8?q?=E7=AE=97=E5=87=BA=E7=9A=84=E8=80=97=E6=97=B6=E5=81=9A=20?= =?UTF-8?q?=E2=80=9C=E9=9D=9E=E8=B4=9F=E6=A0=A1=E9=AA=8C=E2=80=9D=EF=BC=8C?= =?UTF-8?q?=E7=A1=AE=E4=BF=9D=E8=80=97=E6=97=B6=E4=B8=8D=E4=BC=9A=E4=B8=BA?= =?UTF-8?q?=E8=B4=9F=E6=95=B0=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/cn/hutool/core/date/StopWatch.java | 5 ++-- .../cn/hutool/core/date/IssueIDFMXJTest.java | 29 +++++++++++++++++++ 2 files changed, 32 insertions(+), 2 deletions(-) create mode 100644 hutool-core/src/test/java/cn/hutool/core/date/IssueIDFMXJTest.java diff --git a/hutool-core/src/main/java/cn/hutool/core/date/StopWatch.java b/hutool-core/src/main/java/cn/hutool/core/date/StopWatch.java index e83bd25de0..25d3cfcb57 100755 --- a/hutool-core/src/main/java/cn/hutool/core/date/StopWatch.java +++ b/hutool-core/src/main/java/cn/hutool/core/date/StopWatch.java @@ -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); } diff --git a/hutool-core/src/test/java/cn/hutool/core/date/IssueIDFMXJTest.java b/hutool-core/src/test/java/cn/hutool/core/date/IssueIDFMXJTest.java new file mode 100644 index 0000000000..4c43d4ecba --- /dev/null +++ b/hutool-core/src/test/java/cn/hutool/core/date/IssueIDFMXJTest.java @@ -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()); + } +}