/**<p> Project name:</p> * <p> package name:com.zdb.module.test</p> * <p> File name:idworker.java</p> * <p> version information:</p> * <p> Date: 2015-5-23-1:17:49 </p> * Copyright (c) 2015singno Company-All rights reserved */package com.zdb.module.test;/** <p> name:idworker.java</p> * <p> Description: Distributed self-growth id</p> * <pre> * twitter's snowflake Java implementation Solution * </pre> * @author Bao Jianming * @date 2015-5-23 pm 1:17:49 * @version 1.0.0 */public class idworker {private final long workerid;private final static long twepoch = 1288834974657L;private long sequence = 0L; private final static long workeridbits = 4l;public final static long maxworkerid = -1l ^ -1l << workeridbits;private final static long sequencebits = 10l;private final static long workeridshift = sequencebits;private final static long timestampleftshift = sequencebits + workeridbits;public final static long sequencemask = -1l ^ -1l << sequencebits;private long lasttimestamp = -1l;public idworker ( Final long workerid) { super (); if (workerId > this.maxworkerid | | workerid < 0) { throw new IllegalArgumentException (String.Format ( "Worker id can ' t be greater than %d or less than 0 ", this.maxworkerid)); } this.workerid = Workerid;} Public synchronized long nextid () { long timestamp = this.timegen (); if (This.lasttimestamp == timestamp) { this.sequence = (this.sequence + 1) & this.sequenceMask; if (this.sequence == 0) { system.out.println ("########### " + sequencemask"); timestamp = this.tilnextmillis (This.lasttimestamp); } } else { this.sequence = 0; } if (Timestamp < this.lasttimestamp) { try { throw new exception ( string.format ( "Clock moved backwards. refusing to generate id for %d milliseconds ", this.lasttimestamp - timestamp)); } catch (exception e) { e.printstacktrace (); } } this.lastTimestamp = timestamp; long nextId = (timestamp - twepoch << Timestampleftshift)) | ( This.workerid << this.workeridshift) | (this.sequence); System.out.println ("Timestamp:" + timestamp + ", Timestampleftshift:" + timestampLeftShift + ", NextID:" + nextId + ", Workerid:" + workerId + ", Sequence:" &NBSP;+&Nbsp;sequence); return nextid;} Private long tilnextmillis (Final long lasttimestamp) { long timestamp = this.timegen (); while (timestamp <= Lasttimestamp) { timestamp = this.timegen (); } return timestamp;} Private long timegen () { return system.currenttimemillis ();} Public static void main (String[] args) { idworker worker2 = new idworker (2); system.out.println (Worker2.nextid ());}}
Distributed self-Growth ID (Twitter's Snowflake Java implementation Scheme)