#Issue between cache and database on timestamp value

1 messages · Page 1 of 1 (latest)

heady sparrow
#

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.

earnest nacelleBOT
#

<@&987246399047479336> please have a look, thanks.

stuck flax
#

Your function naming seems wrong. setId is more like generateId. Why would you need to remember the previous time you called System.currentTimeMillis? I would suggest using System.nanoTime but the whole idea of whatever you think you need a timestamp for an id begs the question of what you are trying to do (because a UUID solution seems like a better approach perhaps.) Computers today operate in nanoseconds so it more than possible that if you are asking for something in milliseconds (not even microseconds), you will get the same millisecond value because things are moving so fast.