Skip to content

Commit

Permalink
Bugfix: UUIDGenerator generates duplicated id (apache#2972)
Browse files Browse the repository at this point in the history
  • Loading branch information
yujianfei1986 authored and hicf committed Nov 15, 2020
1 parent 920e837 commit b47e3e5
Showing 1 changed file with 9 additions and 10 deletions.
19 changes: 9 additions & 10 deletions common/src/main/java/io/seata/common/util/IdWorker.java
Original file line number Diff line number Diff line change
Expand Up @@ -94,25 +94,24 @@ public IdWorker(long workerId) {
*
* @return SnowflakeId
*/
public long nextId() {
public synchronized long nextId() {
long timestamp = timeGen();

if (timestamp < lastTimestamp) {
throw new RuntimeException(String.format(
"clock moved backwards. Refusing to generate id for %d milliseconds", lastTimestamp - timestamp));
}

synchronized (this) {
if (lastTimestamp == timestamp) {
sequence = (sequence + 1) & sequenceMask;
if (sequence == 0) {
timestamp = tilNextMillis(lastTimestamp);
}
} else {
sequence = 0L;
if (lastTimestamp == timestamp) {
sequence = (sequence + 1) & sequenceMask;
if (sequence == 0) {
timestamp = tilNextMillis(lastTimestamp);
}
lastTimestamp = timestamp;
} else {
sequence = 0L;
}
lastTimestamp = timestamp;

return ((timestamp - twepoch) << timestampLeftShift) | (workerId << workerIdShift) | sequence;
}

Expand Down

0 comments on commit b47e3e5

Please sign in to comment.