new Time UUID - Android java.util

Android examples for java.util:UUID

Description

new Time UUID

Demo Code


import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.UUID;

public class Main{
    /**// ww  w . jav  a  2s .  com
     * The last time value. Used to remove duplicate UUIDs.
     */
    private static long lastTime = Long.MIN_VALUE;
    /**
     * The current clock and node value.
     */
    private static long clockSeqAndNode = 0x8000000000000000L;
    
    public static UUID newTimeUUID() {
        return new UUID(UUIDHelper.createTime(System.currentTimeMillis()),
                UUIDHelper.getClockSeqAndNode());
    }
    /**
     * Creates a new time field from the given timestamp. Note that even identical
     * values of <code>currentTimeMillis</code> will produce different time fields.
     * 
     * @param currentTimeMillis the timestamp
     * @return a new time value
     */
    public static synchronized long createTime(long currentTimeMillis) {

        long time;

        // UTC time

        long timeMillis = (currentTimeMillis * 10000) + 0x01B21DD213814000L;

        if (timeMillis > lastTime) {
            lastTime = timeMillis;
        } else {
            timeMillis = ++lastTime;
        }

        // time low

        time = timeMillis << 32;

        // time mid

        time |= (timeMillis & 0xFFFF00000000L) >> 16;

        // time hi and version

        time |= 0x1000 | ((timeMillis >> 48) & 0x0FFF); // version 1

        return time;

    }
    /**
     * Returns the current clockSeqAndNode value.
     *
     * @return the clockSeqAndNode value
     */
    public static long getClockSeqAndNode() {
        return clockSeqAndNode;
    }
}

Related Tutorials