Document and clean up UUID factory API and implementation.
[lgpl/argeo-commons.git] / org.argeo.api.uuid / src / org / argeo / api / uuid / ConcurrentTimeUuidState.java
index 7d5e6013bcfa5cec798d6866bd57a9d803b56d61..25ba62b03ba4d7224bcc8ec3326838a68b95b9ce 100644 (file)
@@ -8,16 +8,18 @@ import java.security.SecureRandom;
 import java.time.Clock;
 import java.time.Duration;
 import java.time.Instant;
+import java.util.Collections;
+import java.util.Map;
 import java.util.Objects;
 import java.util.Set;
 import java.util.WeakHashMap;
-import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicLong;
 
 /**
  * A simple base implementation of {@link TimeUuidState}, which maintains
  * different clock sequences for each thread.
  */
-public class ConcurrentTimeUuidState implements TimeUuidState {
+public class ConcurrentTimeUuidState implements UuidFactory.TimeUuidState {
        private final static Logger logger = System.getLogger(ConcurrentTimeUuidState.class.getName());
 
        /** The maximum possible value of the clocksequence. */
@@ -33,6 +35,8 @@ public class ConcurrentTimeUuidState implements TimeUuidState {
        private final Clock clock;
        private final boolean useClockForMeasurement;
 
+       private long nodeIdBase;
+
        public ConcurrentTimeUuidState(SecureRandom secureRandom, Clock clock) {
                useClockForMeasurement = clock != null;
                this.clock = clock != null ? clock : Clock.systemUTC();
@@ -42,8 +46,8 @@ public class ConcurrentTimeUuidState implements TimeUuidState {
                // compute the start reference
                startInstant = Instant.now(this.clock);
                long nowVm = nowVm();
-               Duration duration = Duration.between(TimeUuidState.GREGORIAN_START, startInstant);
-               startTimeStamp = durationToUuidTimestamp(duration) - nowVm;
+               Duration duration = Duration.between(TimeUuid.TIMESTAMP_ZERO, startInstant);
+               startTimeStamp = TimeUuid.durationToTimestamp(duration) - nowVm;
 
                clockSequenceProvider = new ClockSequenceProvider(secureRandom);
 
@@ -54,7 +58,7 @@ public class ConcurrentTimeUuidState implements TimeUuidState {
                        protected ConcurrentTimeUuidState.Holder initialValue() {
                                ConcurrentTimeUuidState.Holder value = new ConcurrentTimeUuidState.Holder();
                                value.threadId = Thread.currentThread().getId();
-                               value.lastTimestamp = startTimeStamp;
+                               value.lastTimestamp = 0;
                                clockSequenceProvider.newClockSequence(value);
                                return value;
                        }
@@ -96,8 +100,8 @@ public class ConcurrentTimeUuidState implements TimeUuidState {
 
        private long computeNow() {
                if (useClockForMeasurement) {
-                       Duration duration = Duration.between(TimeUuidState.GREGORIAN_START, Instant.now(clock));
-                       return durationToUuidTimestamp(duration);
+                       Duration duration = Duration.between(TimeUuid.TIMESTAMP_ZERO, Instant.now(clock));
+                       return TimeUuid.durationToTimestamp(duration);
                } else {
                        return startTimeStamp + nowVm();
                }
@@ -107,20 +111,49 @@ public class ConcurrentTimeUuidState implements TimeUuidState {
                return System.nanoTime() / 100;
        }
 
-       private long durationToUuidTimestamp(Duration duration) {
-               return (duration.getSeconds() * 10000000 + duration.getNano() / 100);
+       @Override
+       public long getClockSequence() {
+               return currentHolder.get().clockSequence;
        }
 
        @Override
-       public long getClockSequence() {
-               return (long) currentHolder.get().clockSequence;
+       public long getLastTimestamp() {
+               return currentHolder.get().lastTimestamp;
        }
 
-       private static class Holder {
+       public void reset(long nodeIdBase) {
+               synchronized (clockSequenceProvider) {
+                       this.nodeIdBase = nodeIdBase;
+                       clockSequenceProvider.reset();
+                       clockSequenceProvider.notifyAll();
+               }
+       }
+
+       @Override
+       public long getLeastSignificantBits() {
+               return currentHolder.get().leastSig;
+       }
+
+       @Override
+       public long getMostSignificantBits() {
+               long timestamp = useTimestamp();
+               long mostSig = UuidFactory.MOST_SIG_VERSION1 | ((timestamp & 0xFFFFFFFFL) << 32) // time_low
+                               | (((timestamp >> 32) & 0xFFFFL) << 16) // time_mid
+                               | ((timestamp >> 48) & 0x0FFFL);// time_hi_and_version
+               return mostSig;
+       }
+
+       /*
+        * INTERNAL CLASSSES
+        */
+
+       private class Holder {
                private long lastTimestamp;
-               private int clockSequence;
+               private long clockSequence;
                private long threadId;
 
+               private long leastSig;
+
                @Override
                public boolean equals(Object obj) {
                        boolean isItself = this == obj;
@@ -129,8 +162,13 @@ public class ConcurrentTimeUuidState implements TimeUuidState {
                        return isItself;
                }
 
-               private synchronized void setClockSequence(int clockSequence) {
+               private void setClockSequence(long clockSequence) {
                        this.clockSequence = clockSequence;
+//                     if (nodeIdBase == null)
+//                             throw new IllegalStateException("Node id base is not initialised");
+                       this.leastSig = nodeIdBase // already computed node base
+                                       | (((clockSequence & 0x3F00) >> 8) << 56) // clk_seq_hi_res
+                                       | ((clockSequence & 0xFF) << 48); // clk_seq_low
                }
 
                @Override
@@ -144,11 +182,11 @@ public class ConcurrentTimeUuidState implements TimeUuidState {
                private int rangeSize = 256;
                private volatile int min;
                private volatile int max;
-               private final AtomicInteger counter = new AtomicInteger(-1);
+               private final AtomicLong counter = new AtomicLong(-1);
 
                private final SecureRandom secureRandom;
 
-               private final WeakHashMap<Holder, Integer> activeHolders = new WeakHashMap<>();
+               private final Map<Holder, Long> activeHolders = Collections.synchronizedMap(new WeakHashMap<>());
 
                ClockSequenceProvider(SecureRandom secureRandom) {
                        this.secureRandom = secureRandom;
@@ -156,7 +194,7 @@ public class ConcurrentTimeUuidState implements TimeUuidState {
                }
 
                synchronized void reset() {
-                       int min = secureRandom.nextInt(ConcurrentTimeUuidState.MAX_CLOCKSEQUENCE);
+                       int min = secureRandom.nextInt(ConcurrentTimeUuidState.MAX_CLOCKSEQUENCE - rangeSize);
                        int max = min + rangeSize;
                        if (min >= max)
                                throw new IllegalArgumentException("Minimum " + min + " is bigger than maximum " + max);
@@ -185,11 +223,8 @@ public class ConcurrentTimeUuidState implements TimeUuidState {
                }
 
                private synchronized void newClockSequence(Holder holder) {
-//                     int activeCount = activeHolders.size();
+                       // Too many holders, we will remove the oldes ones
                        while (activeHolders.size() > rangeSize) {
-//                             throw new IllegalStateException(
-//                                             "There are too many holders for range [" + min + "," + max + "] : " + activeCount);
-                               // remove oldest
                                long oldestTimeStamp = -1;
                                Holder holderToRemove = null;
                                holders: for (Holder h : activeHolders.keySet()) {
@@ -214,7 +249,7 @@ public class ConcurrentTimeUuidState implements TimeUuidState {
                                        logger.log(WARNING, "Removed " + holderToRemove + ", oldClockSequence=" + oldClockSequence);
                        }
 
-                       int newClockSequence = -1;
+                       long newClockSequence = -1;
                        int tryCount = 0;// an explicit exit condition
                        do {
                                tryCount++;