From 92a7cad6ddcea4be48ac82cc40f88302b88614d2 Mon Sep 17 00:00:00 2001 From: lookingatstarts Date: Thu, 15 Oct 2020 23:07:56 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E5=A4=8Dbug:=20SnowflakeIDGenImpl#til?= =?UTF-8?q?NextMillis=E6=96=B9=E6=B3=95=EF=BC=8C=E7=AD=89=E5=BE=85?= =?UTF-8?q?=E4=B8=8B=E4=B8=AA=E6=AF=AB=E7=A7=92=E6=97=B6=EF=BC=8C=E5=A6=82?= =?UTF-8?q?=E6=9E=9C=E6=97=B6=E9=92=9F=E5=9B=9E=E8=B0=83=E4=BC=9A=E5=AF=BC?= =?UTF-8?q?=E8=87=B4=E6=96=B9=E6=B3=95=E4=B8=80=E7=9B=B4=E8=BD=AE=E8=AF=A2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../leaf/snowflake/SnowflakeIDGenImpl.java | 26 ++++++++++++++++--- 1 file changed, 22 insertions(+), 4 deletions(-) diff --git a/leaf-core/src/main/java/com/sankuai/inf/leaf/snowflake/SnowflakeIDGenImpl.java b/leaf-core/src/main/java/com/sankuai/inf/leaf/snowflake/SnowflakeIDGenImpl.java index b4f813b2..53595f70 100644 --- a/leaf-core/src/main/java/com/sankuai/inf/leaf/snowflake/SnowflakeIDGenImpl.java +++ b/leaf-core/src/main/java/com/sankuai/inf/leaf/snowflake/SnowflakeIDGenImpl.java @@ -5,10 +5,12 @@ import com.sankuai.inf.leaf.common.Result; import com.sankuai.inf.leaf.common.Status; import com.sankuai.inf.leaf.common.Utils; +import com.sankuai.inf.leaf.snowflake.exception.CheckLastTimeException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Random; +import java.util.concurrent.TimeUnit; public class SnowflakeIDGenImpl implements IDGen { @@ -94,12 +96,28 @@ public synchronized Result get(String key) { } - protected long tilNextMillis(long lastTimestamp) { - long timestamp = timeGen(); - while (timestamp <= lastTimestamp) { + /** + * 等待下个毫秒,防止等待期间系统时钟被回调,导致方法一直轮询 + */ + protected long tilNextMillis(long lastTimestamp){ + long timestamp; + long offset; + while (true) { timestamp = timeGen(); + offset = lastTimestamp-timestamp; + if(offset<0){ + return timestamp; + } + if(offset>=5) { // 系统时钟回调时间大于5ms + throw new CheckLastTimeException("timestamp check error,last timestamp " + lastTimestamp + ",now " + timestamp); + } + if(offset>=2){ // 系统时钟回调时间大于等于2ms + try { + TimeUnit.MILLISECONDS.sleep(offset); + } catch (InterruptedException ignore) { + } + } } - return timestamp; } protected long timeGen() {