SNOWFLAKE__ algorithm for self-increasing ID algorithm

Source: Internet
Author: User

The background of the Twitter-snowflake algorithm is quite simple, and in order to satisfy Twitter's request for tens of thousands of messages per second, each message must be assigned a unique ID, which requires some sort of approximate order (convenient for client ordering), And the IDs produced by different machines in the distributed system must be different.

Snowflake generates a 64 ID, which is saved just by using a long structure as follows:

1-bit ID, since the long base type is signed in Java, the highest digit is the sign bit, the positive number is 0, and the negative number is 1, so the ID is generally positive and the highest digit is 0

41-bit time truncation, note that 41-bit time truncation is not the time to store the current time, but rather the time to store the difference (the current time cut-start time truncation of the value), where the Start time section, is usually the time our ID generator began to use, specified by our program (the following program idworker the StartTime attribute of the Class). 41-bit time cut, can be used 69 years, T = (1L <<)/(1000L * 60 * 60 * 24 * 365) = 69

10-bit data machine bit that can be deployed on 1024 nodes

12-bit sequence, same time cut, same machine, can generate 4,096 IDs

Using Java implementation:

public class Idworker {//the time at which the class generated the ID is truncated private final long starttime = 1463834116272L;
	
	Number of digits of machine ID private long workeridbits = 5L;
	
	Number of digits of the data ID ID private long datacenteridbits = 5L;
	
	Maximum supported machine ID private long Maxworkerid = -1l ^ ( -1l << workeridbits);
	
	Maximum supported data ID private Long Maxdatacenterid = -1l ^ ( -1l << datacenteridbits);
	
	Number of digits in the ID of the sequence private long sequencebits = 12L;
	
	Number of digits to the left of the machine ID private long workeridleftshift = sequencebits;
	
	Number of digits to the left of the data ID ID private Long datacenteridleftshift = Workeridbits + workeridleftshift;
	
	The position of the time truncation to the left is private long Timestampleftshift = Datacenteridbits + datacenteridleftshift;
	
	Mask of the generated sequence private long Sequencemask =-1 ^ ( -1 << sequencebits);
	
	Private long Workerid;
	
	Private long Datacenterid;
	
	The number of sequences generated in the same time section, the initial value is 0, starting from 0 private long sequence = 0L;
	
	The last time the ID was generated was truncated private long lasttimestamp = -1l; Public Idworker (Long Workerid, long Datacenterid) {if (Workerid < 0 | | Workerid > Maxworkerid) {
			throw new IllegalArgumentException (String.Format ("workerid[%d" is less than 0 or greater than maxworkerid[%d].
		", Workerid, Maxworkerid)); } if (Datacenterid < 0 | | Datacenterid > Maxdatacenterid) {throw new IllegalArgumentException (String.Format
		("datacenterid[%d] is less than 0 or greater than maxdatacenterid[%d].", Datacenterid, Maxdatacenterid));
		} This.workerid = Workerid;
	This.datacenterid = Datacenterid;
		}//Generate ID public synchronized long NextID () {Long timestamp = Timegen ();  if (Timestamp < Lasttimestamp) {throw new RuntimeException (String.Format ("Clock moved.
		Refusing to generate ID for%d milliseconds ", lasttimestamp-timestamp));
			}//indicates that the ID if (timestamp = lasttimestamp) {sequence = (sequence + 1) is generated in the same time section & Sequencemask;
				Indicates that the current time generated sequence number has reached the maximum if (sequence = = 0) {//generation of the next millisecond sequence timestamp = Tilnextmillis ();
			The sequence begins with 0 sequence = 0L;
		}else{//New time cut, then the sequence starts from 0 sequence = 0L; }
		
		Lasttimestamp = timestamp; Return ((timestamp-starttime) << timestampleftshift)//Time Section | (Datacenterid << Datacenteridleftshift)//Data ID Part | (Workerid << Workeridleftshift)//Machine ID Part | Sequence
		Sequence part} protected long Tilnextmillis () {Long timestamp = Timegen ();
		while (timestamp <= lasttimestamp) {timestamp = Timegen ();
	return timestamp;
	Protected long Timegen () {return system.currenttimemillis ();
		//test public static void main (string[] args) {Idworker idworker = new Idworker (31, 31);
		for (int i = 0; i < 1000 i++) {System.out.println (Idworker.nextid ()); }
	}

}

Transferred from

http://www.lanindex.com/twitter-snowflake%EF%BC%8C64%E4%BD%8D%E8%87%AA%E5%A2%9Eid%E7%AE%97%E6%B3%95%E8%AF%A6%E8%A7%A3/

Http://www.devnote.cn/article/420.html


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.