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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With