getId method

int getId()

Implementation

int getId() {
  int timestamp = currentTimeStamp;

  // 如果当前时间小于上一次ID生成的时间戳,说明系统时钟回退过这个时候应当抛出异常
  if (timestamp < _lastTimestamp) {
    throw Exception(
        "Clock moved backwards.  Refusing to generate id for ${_lastTimestamp - timestamp} milliseconds");
  }

  // 如果是同一时间生成的,则进行秒内序列
  if (_lastTimestamp == timestamp) {
    _sequence = (_sequence + 1) & _sequenceMask;
    // 秒内序列溢出
    if (_sequence == 0) {
      // 阻塞到下一个秒,获得新的时间戳
      timestamp = untilNextMillis(_lastTimestamp);
    }
  }
  // 时间戳改变,秒内序列重置
  else {
    _sequence = 0;
  }

  // 上次生成ID的时间截
  _lastTimestamp = timestamp;

  // 移位并通过或运算拼到一起组成64位的ID
  return ((timestamp - _twepoch) << _timestampeftShift) |
      (_datacenterId << _datacenterIdShift) |
      (_workerId << _workerIdShift) |
      _sequence;
}