Does it make sense to synchronize java virtual machines with System.nanoTime () ?
I mean :
- A call System.nanoTime () and puts the results in t1
- A send a packet to B
- when the packet from A is received on B, B call System.nanoTime() and sends the result to A
- when the packet from B is received on A, A call System.nanoTime () and puts the results in t3, puts the time received in the packet from B in t2
- timeshift = (t3 - t1) / 2 - t2
is it correct to use System.nanoTime to do that ?
thanks !
No.
System.nanoTime()
is only useful for measuring time differences within a single JVM, not absolute time across multiple JVMs.To solve that problem, in general you'd use
System.currentTimeMillis()
, but that's still limited by the OS clocks of the two computers. Use NTP to synchronize time across computers.See Time synchronization between server and Internet using Java.