Can nanoTime work on threads

I have a thread that pushes data into a queue and another thread that reads data from the queue and processes it. I would like to check how long the data is in the queue before processing.

I added a time parameter (calculated using System.nanoTime() ) in the data before being clicked by the first thread. As soon as the second thread processes it, it will calculate System.nanoTime() and find the difference with the previous time set in the data.

Will this work correctly? I ask about this because I see a negative difference in the magazines.

UPDATE

I would like to clarify that the start time is set by a process on another machine, and the difference is calculated on another machine.

+6
source share
1 answer

I used System.nanoTime () between threads and processes. On one machine, it grows globally and monotonously (with the exception of multi-node Windows XP)

If you see a negative difference, this is most likely an error in your code.

You can see nanoTime () between machines, but you need to adjust the difference and drift between the clocks. (And you can get great very negative results if you don't make this correction)

the start time is set by the process on another machine, and the difference is calculated on another machine.

Between machines you need either

  • use System.currentTimjeMillis (), which is usually millisecond accurate with NTP.
  • use System.nanoTime () to travel back and forth, that is, send a message from A ro B, and the other back to A. The half-time of the trip can be estimated from this.
  • use System.nanoTime () not for time, but for jitter detection. This suggests that most of the delay time is acceptable (say, 10 to 100 microseconds), but sometimes it is much higher than usual. I use this class to help detect jitter. Runningminimum

If you are only interested in multi-million delays, I would use currentTimeMillis ()

+4
source

All Articles