- private final static int MAX_CLOCKSEQUENCE = 16384;
-
- private final static SecureRandom SECURE_RANDOM;
- private final static Random UNSECURE_RANDOM;
- private final static byte[] HARDWARE_ADDRESS;
-
- private final static AtomicInteger CLOCK_SEQUENCE;
-
- /** A start timestamp to which {@link System#nanoTime()}/100 can be added. */
- private final static long START_TIMESTAMP;
-
- static {
- SECURE_RANDOM = new SecureRandom();
- UNSECURE_RANDOM = new Random();
- CLOCK_SEQUENCE = new AtomicInteger(SECURE_RANDOM.nextInt(MAX_CLOCKSEQUENCE));
- HARDWARE_ADDRESS = getHardwareAddress();
-
- long nowVm = System.nanoTime() / 100;
- Duration duration = Duration.between(GREGORIAN_START, LocalDateTime.now(ZoneOffset.UTC));
- START_TIMESTAMP = (duration.getSeconds() * 10000000 + duration.getNano() / 100) - nowVm;
- }
-
- /*
- * TIME-BASED (version 1)
- */
-
- private static byte[] getHardwareAddress() {
- InetAddress localHost;
- try {
- localHost = InetAddress.getLocalHost();
- try {
- NetworkInterface nic = NetworkInterface.getByInetAddress(localHost);
- return nic.getHardwareAddress();
- } catch (SocketException e) {
- return null;
- }
- } catch (UnknownHostException e) {
- return null;
- }
-
- }
-
- private synchronized static long nextClockSequence() {
- int i = CLOCK_SEQUENCE.incrementAndGet();
- while (i < 0 || i >= MAX_CLOCKSEQUENCE) {
- CLOCK_SEQUENCE.set(SECURE_RANDOM.nextInt(MAX_CLOCKSEQUENCE));
- i = CLOCK_SEQUENCE.incrementAndGet();
- }
- return (long) i;
- }
-
- public static UUID timeUUIDwithRandomNode() {
- long timestamp = START_TIMESTAMP + System.nanoTime() / 100;
- return timeUUID(timestamp, SECURE_RANDOM);
- }
-
- public static UUID timeUUIDwithUnsecureRandomNode() {
- long timestamp = START_TIMESTAMP + System.nanoTime() / 100;
- return timeUUID(timestamp, UNSECURE_RANDOM);
- }
-
- public static UUID timeUUID(long timestamp, Random random) {
- byte[] node = new byte[6];
- random.nextBytes(node);
- node[0] = (byte) (node[0] | 1);
- long clockSequence = nextClockSequence();
- return timeUUID(timestamp, clockSequence, node);
- }
-
- public static UUID timeUUID() {
- long timestamp = START_TIMESTAMP + System.nanoTime() / 100;
- return timeUUID(timestamp);
- }
-
- public static UUID timeUUID(long timestamp) {
- if (HARDWARE_ADDRESS == null)
- return timeUUID(timestamp, SECURE_RANDOM);
- long clockSequence = nextClockSequence();
- return timeUUID(timestamp, clockSequence, HARDWARE_ADDRESS);
- }