From a3eca85e12db8b5a2d80f1511b6923c27f376463 Mon Sep 17 00:00:00 2001 From: jptx1234 Date: Sun, 17 May 2020 23:29:43 +0800 Subject: [PATCH] =?UTF-8?q?Snowflake=20=E5=BE=AA=E7=8E=AF=E7=AD=89?= =?UTF-8?q?=E5=BE=85=E4=B8=8B=E4=B8=80=E4=B8=AA=E6=97=B6=E9=97=B4=E6=97=B6?= =?UTF-8?q?=E5=8A=A0=E5=85=A5=E5=AF=B9=E6=97=B6=E9=92=9F=E5=80=92=E9=80=80?= =?UTF-8?q?=E7=9A=84=E5=88=A4=E6=96=AD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Snowflake 在循环等待下一个时间时,判断时间未发生变化的方式由<=改为==,避免了时钟突然倒退导致的长时间循环,同时加入时钟倒退检测,避免生成重复ID --- .../src/main/java/cn/hutool/core/lang/Snowflake.java | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/hutool-core/src/main/java/cn/hutool/core/lang/Snowflake.java b/hutool-core/src/main/java/cn/hutool/core/lang/Snowflake.java index b39ddb3bd..44908d7d0 100644 --- a/hutool-core/src/main/java/cn/hutool/core/lang/Snowflake.java +++ b/hutool-core/src/main/java/cn/hutool/core/lang/Snowflake.java @@ -177,9 +177,15 @@ public class Snowflake implements Serializable { */ private long tilNextMillis(long lastTimestamp) { long timestamp = genTime(); - while (timestamp <= lastTimestamp) { + // 循环直到操作系统时间戳变化 + while (timestamp == lastTimestamp) { timestamp = genTime(); } + if (timestamp < lastTimestamp) { + // 如果发现新的时间戳比上次记录的时间戳数值小,说明操作系统时间发生了倒退,报错 + throw new IllegalStateException( + StrUtil.format("Clock moved backwards. Refusing to generate id for {}ms", lastTimestamp - timestamp)); + } return timestamp; }