Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Duplicate millisecond timestamp issue

I am trying to rapidly publish messages to my server via Websockets. For each message the server gets I store it in the form "timestamp: message" in my HashMap. I need HashMaps for returning the history of messages in chronological order with the timestamp needed. (Any other data structure recommendation is welcome.)

It so happens that when I rapidly publish messages, two or more messages have the same timestamp and hence I cannot save them. I'm already using System.currentTimeMillis(). I cannot go into Nanoseconds are I read the value is arbitrary and often unreliable.

I have tried appending a static AtomicInteger variable at the end of the timestamps and it works but, when I return the messages to my user I need to return a JSON and again I'm not able to store duplicate key.

How can I tackle this problem?

like image 763
Gaurav Bhor Avatar asked Nov 23 '25 16:11

Gaurav Bhor


1 Answers

do you need an absolute timestamp? maybe a counter - i.e. knowing a arrived before b - is enough, have a counter which you increment when a message arrives and use that as your 'timestamp'. no more duplicates and the chronological order is still intact.

furthermore, you could also just use a FIFO queue if you do not insist on having a map. this will also keep chronological order.

like image 171
kmera Avatar answered Nov 25 '25 08:11

kmera