Java implementation of the Snowflake generation UUID (Java code Combat-007)

Source: Internet
Author: User

The IDs generated by Snowflake are divided into four parts:

1. First place
Consumes 1bit, and its value is always 0, with no practical effect.

2. Time stamp
Takes up to 41bit, accurate to milliseconds, and can hold a total of approximately 69 years.

3. Work Machine ID
Occupy 10bit, where high 5bit is the data center ID (datacenterid), low 5bit is the work Node ID (workerid), long can accommodate 1024 nodes.

4. Serial number
Occupies 12bit, this value is accumulated from 0 on the same node in the same millisecond, and can accumulate up to 4095.

How many globally unique IDs can the snowflake algorithm generate in the same millisecond? You just need to do a simple multiplication:

Number of IDs in the same millisecond = 1024x768 X 4096 = 4194304

This number is sufficient for most concurrent scenarios.

ImportJava.util.concurrent.ExecutorService;Importjava.util.concurrent.Executors;/*** Created by Xfyou 2018/6/8 14:01.*/ Public classSnowflakeidgenerator {//The initial time (2017-01-01)    Private Static Final LongInitial_time_stamp = 1483200000000L; //Machine ID bits    Private Static Final LongWork_id_bits = 5L; //DataCenter ID bits    Private Static Final LongDatacenter_id_bits = 5L; //The maximum machine ID supported are, which can quickly calculate the maximum decimal number that a few binary num Bers can represent.    Private Static Final Longmax_worker_id = ~ ( -1l <<work_id_bits); //The maximum Datacenter ID supported is    Private Static Final Longmax_datacenter_id = ~ ( -1l <<datacenter_id_bits); //Sequence ID bits    Private Static Final LongSequence_bits = 12L; //The machine ID offset,12    Private Static Final LongWorkerid_offset =sequence_bits; //The datacent ID offset,12+5    Private Static Final LongDatacenterid_offset = Work_id_bits +sequence_bits; //the Timestape offset, 5+5+12    Private Static Final LongTimestamp_offset = datacenter_id_bits + work_id_bits +sequence_bits; //Sequence mask,4095    Private Static Final LongSequence_mask = ~ ( -1l <<sequence_bits); //Worker ID, 0~31    Private LongWorkerid; //Datacenter id,0~31    Private LongDatacenterid; //sequence,0~4095    Private Longsequence = 0L; //Last timestamp    Private LongLasttimestamp = -1l;  PublicSnowflakeidgenerator (LongWorkerid,LongDatacenterid) {        if(Workerid > max_worker_id | | Workerid < 0)            Throw NewIllegalArgumentException (String.Format ("Workerid can ' t be greater than%d or less than 0", max_worker_id)); if(Datacenterid > max_datacenter_id | | Datacenterid < 0)            Throw NewIllegalArgumentException (String.Format ("Datacenterid can ' t be greater than%d or less than 0", max_worker_id));  This. Workerid =Workerid;  This. Datacenterid =Datacenterid; }     Public synchronized LongNextID () {LongTimeStamp =System.currenttimemillis (); if(TimeStamp <Lasttimestamp)Throw NewRuntimeException ("The current time less than last time"); if(TimeStamp = =Lasttimestamp) {Sequence= (sequence + 1) &Sequence_mask; if(0 = =sequence) TimeStamp=Tillnextmillis (Lasttimestamp); } Else{sequence= 0L; } Lasttimestamp=TimeStamp; return(timestamp-initial_time_stamp) << Timestamp_offset | (Datacenterid << Datacenterid_offset) | (Workerid << Workerid_offset) |sequence; }    Private LongTillnextmillis (LongLasttimestamp) {        Longtimestamp =System.currenttimemillis ();  while(Timestamp <=lasttimestamp) Timestamp=System.currenttimemillis (); returntimestamp; }     Public Static voidMain (string[] args) {Snowflakeidgenerator generator=NewSnowflakeidgenerator (1, 1); Executorservice Executorservice=Executors.newcachedthreadpool ();  for(inti = 0; I < 5; i++) {Executorservice.execute (NewRunnable () {@Override Public voidrun () {LongID =Generator.nextid ();                SYSTEM.OUT.PRINTLN (ID);        }            });    } executorservice.shutdown (); }}

One possible output is:

189783462515970048189783462515970049189783462515970050189783462515970051189783462520164352

Java implementation of the Snowflake generation UUID (Java code Combat-007)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.