Hi there,
I hope you're doing fine, I wrote the following code:
public class DefaultDataHandler extends BaseDataHandler {
...
@Override
protected Position handlePosition(Position position) {
long snowflakeId = SNOWFLAKE_ID_GENERATOR.setId();
position.setId(snowflakeId);
try {
storage.addObject(position, new Request(new Columns.All()));
} catch (Exception error) {
LOGGER.warn("Failed to store position", error);
}
return position;
}
}
public synchronized long setId() {
long currentTimestamp = System.currentTimeMillis() - customEpoch;
if (currentTimestamp < lastTimestamp) {
throw new IllegalStateException("Invalid System Clock!");
}
if (currentTimestamp == lastTimestamp) {
sequence = (sequence + 1) & MAX_SEQUENCE;
if (sequence == 0) {
// Sequence Exhausted, wait till next millisecond.
currentTimestamp = waitNextMillis(currentTimestamp);
}
} else {
// reset sequence to start with zero for the next millisecond
sequence = 0;
}
lastTimestamp = currentTimestamp;
long id = currentTimestamp << (NODE_ID_BITS + SEQUENCE_BITS)
| (nodeId << SEQUENCE_BITS)
| sequence;
return id;
}
I'm facing a problem with data consistency between my cache and database. When I insert an ID, the values in both locations aren't always identical. While they sometimes match, there's usually a slight difference in milliseconds.
Since I'm not a Java expert, I suspect multithreading might be causing the issue. However, I'm limited in my ability to investigate further.