0

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.

Martin L.
  • 3,006
  • 6
  • 36
  • 60
  • 1
    Optimization is not going to help you here (unless all of the time is consumed by "do some processing"). There is [real-time Java](http://en.wikipedia.org/wiki/Real_time_Java), which should be able to ensure that your `send()` occurs on a fixed interval ("real-time" is about precision, not performance). However, this won't help with network delays. – kdgregory Mar 25 '13 at 12:49
  • Oh that's interesting, thank you. I will study this resources. The "do some processing" is not time-intensive, it just copies some bytes from a queue into the udp-paket :) – Martin L. Mar 25 '13 at 12:53
  • 1
    Check the influence of logging; say registring 1000 times and logging 1 in 1000. – Joop Eggen Mar 25 '13 at 12:54

1 Answers1

1

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)

Brian Agnew
  • 268,207
  • 37
  • 334
  • 440