Skip to content

Reduce synchronization scope when generating the TSID #25

@vladmihalcea

Description

@vladmihalcea

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions