la idea de cambio de bit en twitter copo de nieve IdWorker

who can explain code that it's the core of the twitter snowflake.

long nextId = ((timestamp - twepoch) << this.timestampLeftShift)
            | (this.workerId << this.workerIdShift) | (this.sequence);

i want to know that the think of the algorithm,why does it implement?

preguntado el 02 de julio de 12 a las 02:07

1 Respuestas

Twitter's snowflake service creates unique ids in a distributed environment. A number of worker processes can each assign unique ids. The ids consist of three components: the time, a worker id, and a sequence number. The line of code you show simple shifts those three components so that they don't overlap in the 64-bit result, and or's them together to create a single 64-bit result.

Respondido 02 Jul 12, 03:07

hi,Ned Batchelder,That means i can change its algorithm by myself such as the under of code: long nextId = ((timestamp - twepoch) << 2) | (this.workerId << 3) | (this.sequence<<5); and is it that as your answer? - snageyang

im test the above of the code by concurrency 10 thread:long nextId = ((timestamp - twepoch) << 2) | (this.workerId << 3) | (this.sequence<<5),the result of id can be repeat,whats about the code. - snageyang

I didn't say you could change the code willy-nilly and it would continue to work. The shift amounts depend on the size of the three components. It's important that they not overlap. - Ned Batchelder

i cant unstand that the left shift amounts about timestampLeftShift,workerIdShift and why the sequence do not left shift? thanks. - snageyang

@snageyang: I have no idea what you are trying to accomplish. Experiment with different values of shifting to see what they do. - Ned Batchelder

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.