private static final long ONE_STEP = 10; private static final long BASE = 1129703383453l;
private static final Lock LOCK = new ReentrantLock();
private static long lastTime = System.currentTimeMillis(); private static short lastCount = 0;
/** * a time (as returned by {@link System#currentTimeMillis()}) at which * the VM that this UID was generated in was alive * @serial */ private final long time;
/** * 16-bit number to distinguish UID instances created * in the same VM with the same time value * @serial */ private final short count;
/** * Generates a UID that is unique over time with * respect to the host that it was generated on. */ public UID() { LOCK.lock(); try { if (lastCount == ONE_STEP) { boolean done = false; while (!done) { long now = System.currentTimeMillis(); if (now == lastTime) { // pause for a second to wait for time to change try { Thread.currentThread().sleep(1); } catch (java.lang.InterruptedException e) { } // ignore exception continue; } else { lastTime = now; lastCount = 0; done = true; } } } time = lastTime; count = lastCount++; } finally { LOCK.unlock(); } } 在一个群集的环境里面,通常还需要加上ip的前缀,即 IP + 时间 + 计数器,这个就是JAVA原版本的实现了。