Extreme precise repeated/continuous code-execution

113 views Asked by At

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.

1

There are 1 answers

1
Brian Agnew On

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)