Clover icon

sunshower-base

  1. Project Clover database Fri Apr 6 2018 03:41:27 UTC
  2. Package io.sunshower.persist

File IDSequence.java

 

Coverage histogram

../../../img/srcFileCovDistChart7.png
25% of files have more coverage

Code metrics

6
25
6
1
91
70
10
0.4
4.17
6
1.67

Classes

Class Line # Actions
IDSequence 9 25 10
0.675675767.6%
 

Contributing tests

This file is covered by 11 tests. .

Source view

1    package io.sunshower.persist;
2   
3    import io.sunshower.common.Identifier;
4    import java.net.InetAddress;
5    import java.nio.ByteBuffer;
6    import java.time.Clock;
7    import java.util.Objects;
8   
 
9    final class IDSequence implements Sequence<Identifier>, NodeAware, TimeBased {
10   
11    static final int ID_SIZE = 16;
12   
13    static final int NODE_SIZE = 6;
14   
15    static final int SEQUENCE_MAXIMUM = 0xFFFF;
16   
17    final Object sequenceLock = new Object();
18   
19    final Clock clock;
20   
21    final InetAddress node;
22   
23    final InetAddress nodeIdentity;
24   
25    final byte[] seed;
26   
27    private volatile int sequence;
28   
29    private volatile long currentTime;
30   
31    private volatile long previousTime;
32   
33    private final boolean applyBackpressure;
34   
 
35  19 toggle public IDSequence(Clock clock, byte[] seed, InetAddress node, boolean applyBackpressure) {
36  19 check(clock, node);
37  19 this.node = node;
38  19 this.clock = clock;
39  19 this.seed = seed;
40  19 this.nodeIdentity = node;
41  19 this.applyBackpressure = applyBackpressure;
42    }
43   
 
44  101909 toggle @Override
45    public Identifier next() {
46  101909 synchronized (sequenceLock) {
47  101909 increment();
48  101909 ByteBuffer sequenceBytes = ByteBuffer.allocate(ID_SIZE);
49  101909 return Identifier.valueOf(
50    sequenceBytes.putLong(currentTime).put(seed).putShort((short) sequence).array());
51    }
52    }
53   
 
54  101909 toggle private void increment() {
55  101909 currentTime = clock.millis();
56   
57  101909 if (currentTime != previousTime) {
58  1650 sequence = 0;
59  1650 previousTime = currentTime;
60  100259 } else if (sequence == SEQUENCE_MAXIMUM) {
61  0 if (applyBackpressure) {
62  0 try {
63  0 Thread.sleep(1);
64  0 increment();
65    } catch (InterruptedException ex) {
66    }
67    }
68  0 throw new IllegalArgumentException(
69    "Attempting to generate sequences too quickly. "
70    + "Can't guarantee uniqueness. "
71    + "Try using another sequence instance (with another clock)");
72    } else {
73  100259 sequence++;
74    }
75    }
76   
 
77  0 toggle @Override
78    public Clock getClock() {
79  0 return clock;
80    }
81   
 
82  0 toggle @Override
83    public InetAddress getNodeIdentity() {
84  0 return nodeIdentity;
85    }
86   
 
87  19 toggle private void check(Clock clock, InetAddress node) {
88  19 Objects.requireNonNull(node, "Node must not be null!");
89  19 Objects.requireNonNull(clock, "Clock must not be null!");
90    }
91    }