Created
January 28, 2015 13:41
-
-
Save mathieuancelin/7e27c54269eedbc85293 to your computer and use it in GitHub Desktop.
Générateur d'id uniques ordonnés distribués (~1000 id générés par milliseconde par noeud)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| public class KOrderedIdGenerator { | |
| private final JsonConfiguration config = JsonConfiguration.fromBlob("...."); // à prendre dans la conf play | |
| private final Long generatorId = config.getLong("generator.id", 1L); // propre à chaque noeud, d'où le k-ordered | |
| private final Long minus = 1288834974657L; | |
| private final AtomicLong counter = new AtomicLong(-1L); | |
| private final AtomicLong lastTimestamp = new AtomicLong(-1L); | |
| {{ | |
| if (generatorId > 1024L) throw new RuntimeException("Worker id can't be larger than 1024"); | |
| }} | |
| public synchronized Long nextId() { | |
| long timestamp = System.currentTimeMillis(); | |
| if (timestamp < lastTimestamp.get()) throw new RuntimeException("Clock is running backward. Sorry :-("); // au cas ou NTP se synchronise vers le passé | |
| lastTimestamp.set(timestamp); | |
| counter.compareAndSet(4095, -1L); | |
| return ((timestamp - minus) << 22L) | (generatorId << 10L) | counter.incrementAndGet(); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment