Currently, the TsidFactory.create method is synchronized:
public synchronized Tsid create() {
final long _time = getTime() << RANDOM_BITS;
final long _node = (long) this.node << this.counterBits;
final long _counter = (long) this.counter & this.counterMask;
return new Tsid(_time | _node | _counter);
}
But, the synchronized is needed for getTime only. So, it is getTime that should be synchronized instead because of the timestamp monotonicity issues:
private synchronized long getTime() {
long time = clock.millis();
if (time <= this.lastTime) {
this.counter++;
// Carry is 1 if an overflow occurs after ++.
int carry = this.counter >>> this.counterBits;
this.counter = this.counter & this.counterMask;
time = this.lastTime + carry; // increment time
} else {
// If the system clock has advanced as expected,
// simply reset the counter to a new random value.
this.counter = this.getRandomCounter();
}
// save current time
this.lastTime = time;
// adjust to the custom epoch
return time - this.customEpoch;
}
This will reduce the scope of the Thread contention, especially when using a ThreadLocalRandom generator.
Currently, the
TsidFactory.createmethod is synchronized:But, the
synchronizedis needed forgetTimeonly. So, it isgetTimethat should besynchronizedinstead because of the timestamp monotonicity issues:This will reduce the scope of the Thread contention, especially when using a
ThreadLocalRandomgenerator.