public synchronized long nextId ( ) { long currTimestamp = timestampGen ( ) ; if ( currTimestamp < lastTimestamp ) { throw new IllegalStateException ( String . format ( "Clock moved backwards. Refusing to generate id for %d milliseconds" , lastTimestamp - currTimestamp ) ) ; } if ( currTimestamp == lastTimestamp ) { sequence = ( sequence + 1 ) & maxSequence ; if ( sequence == 0 ) { // overflow: greater than max sequence currTimestamp = waitNextMillis ( currTimestamp ) ; } } else { // reset to 0 for next period/millisecond sequence = 0L ; } // track and memo the time stamp last snowflake ID generated lastTimestamp = currTimestamp ; return ( ( currTimestamp - epoch ) << timestampShift ) | // ( datacenterId << datacenterIdShift ) | // ( workerId << workerIdShift ) | // new line for nice looking sequence ; }
generate an unique and incrementing id