Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

修复bug: SnowflakeIDGenImpl#tilNextMillis方法,等待下个毫秒时,如果时钟回调会导致方法一直轮询 #153

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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 {

Expand Down Expand Up @@ -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() {
Expand Down