2
votes

I have application which stores received UDP packets in file, with storing receive time of each packet along with each packet. I am using System.currentTimeMillies() to get receive time when packet is received.

I need to store time, so because, when I transmit this file on UDP, I will transmit each packets from file, synchronizing with time stored for each packet.

The problem is, if I change system date and time while receiving and storing packets, synchronization while sending file gets messed up.

So I need timestamping each received packet independent of system date and time. So that while sending, sending rate will be synchronized even if system date and time was changed while receiving.

I know these can be achieved with System.nanoTime(), but is it safe to use this? I think System.nanoTime() may not be accurate over different system architecture and operating systems.

Also, if I use System.nanoTime(), how this clock will start (initial value), because I do not want it to end with last value while program is running. If from the first call to System.nanoTime() clock starts from 0, this clock can run for around 290 years before ending with last value.

Is there any alternative to System.nanoTime()? I need accuracy of clock in milliseconds.

Also I need this clock to run independent of system, because I may be transmitting file from other machine. Also, it should not skew time for days or months, never between different systems.

Thanks

1
Why don't you put the sent date inside your UDP packets ?Julien
The application which sends UDP, is not in my control. I can't modify that application.nullptr

1 Answers

1
votes

System.nanoTime() is the only way (within the JDK) to get a date that won't change if your system's date is changed.

To deal with overflows (assuming your system will run less than 290 years), use an arbitrary starting point and store differences:

public static final long START = System.nanoTime();

//when receiving packet:
long date = System.nanoTime();
packet.setTimestamp(date - START);