Package util;/** * Snowflake Algorithm * * @author Zengwei * @email [email protected] * @date 2018-03-25 22:02 */public class Idwork Er {private final long workerid; Private final long Snsepoch = 1330328109047L; Private long sequence = 0L; Private final long workeridbits = 10L; Private final Long Maxworkerid = -1l ^ -1l << this.workeridbits; Private final long sequencebits = 12L; Private final long workeridshift = this.sequencebits; Private final Long Timestampleftshift = this.sequencebits + this.workeridbits; Private final Long Sequencemask = -1l ^ -1l << this.sequencebits; Private long lasttimestamp = -1l; Public Idworker (Long Workerid) {super (); if (Workerid > This.maxworkerid | | Workerid < 0) {throw new IllegalArgumentException (String.Format ("work Er Id can ' t is greater than%d or less than 0 ", This.maxworkerid)); } This.workerid = Workerid; } Public synchronized Long NextID () throws Exception { Long timestamp = This.timegen (); if (This.lasttimestamp = = timestamp) {this.sequence = this.sequence + 1 & this.sequencemask; if (this.sequence = = 0) {timestamp = This.tilnextmillis (This.lasttimestamp); }} else {this.sequence = 0; } if (timestamp < This.lasttimestamp) {throw new Exception (String.Format ("Clock moved backwards. Refusing to generate ID for%d milliseconds ", (This.lasttimestamp-timestamp))); } This.lasttimestamp = timestamp; return Timestamp-this.snsepoch << This.timestampleftshift | This.workerid << This.workeridshift | This.sequence; }/** * Guarantees the number of milliseconds returned after the parameter * * @param lasttimestamp * @return */Private long tilnextmillis (long Las Ttimestamp) {Long timestamp = This.timegen (); while (timestamp <= lasttimestamp) {timestamp = This.timegen (); } return timeStamp }/** * Gets the current number of milliseconds in the system * * @return */Private Long Timegen () {return system.currenttimemillis (); } public static void Main (string[] args) {Integer workid = 1; Idworker idwork = new Idworker (workid); try {System.out.println (string.valueof-Idwork.nextid ())); } catch (Exception e) {e.printstacktrace (); } }}
JAVA Snowflake algorithm