In my company, I have a program which must send some data via UDP to a remote system not under our control.
The data must be send every 7981859ns (=7.98 milliseconds) +/- 0.001ms .
Sadly, older versions of that remote-system are breaking if we transmit the data too late, and our side runs out of data if we transmit too fast/early (realtime data-generation).
At the moment, we're sending the UDP-paket via
private Runnable sendData() {
return new Runnable() {
byte[] b = new byte[2000];
DatagramPacket packet = new DatagramPacket(b, b.length);
public void run() {
// do some processing and fill the DatagramPacket
// (..)
packet.setData(data);
packet.setSocketAddress(address);
socket.send(packet);
Log.debug("log time here")
}
};
}
threadPoolExecutor = new ScheduledThreadPoolExecutor(3);
threadPoolExecutor.scheduleAtFixedRate(sendData(), 7981859, 7981859, TimeUnit.NANOSECONDS);
If I add some logging, I can see that the data is send in between 6ms - 11ms, which is a too large range for us.
I now wondered how to optimize this.
Is it maybe possible to set a variable with the nano-timestamp of the last transmit (how get that? I just know System.currentTimeMillis())
, execute the loop a bit faster (or just in a while(true)
-loop) and then wait until "currentNanoTime - lastNanoTime > 7981859" before doing the send(..)
?
My problem was that I didn't find a way to wait nanoseconds, just milliseconds.
I can't help thinking this is not going to be practical.
Leaving aside the fact that Java is not a real time environment (different threads running, performing garbage collection etc.), can you guarantee that your UDP packets can arrive with the stated precision ? UDP delivery is not guaranteed, let alone having any concept of QoS (quality of service)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.