I have an integration test that needs to coordinate two DatagramSockets, each running in their own thread. One socket waits to read data with a blocking call to receive(). The other socket needs to call send(), but this must happen after receive() has blocked, otherwise the data will be lost.
The code is a little like this:
Receiver
byte[] buf = new byte[1024];
new DatagramSocket(7654).receive(new DatagramPacket(buf, buf.length));
Sender
new DatagramSocket(7654).send(
new DatagramPacket("hello".getBytes(Charset.forName("UTF-8")), 5));
I’m loath to put a Thread.sleep() before the send() call, although this would probably be sufficient to allow the receiver to block. Is there an elegant way to do this?
Wait on a semaphore just before the send(). Signal a unit just before the receive() call. Given network delays, I would be amazed if a UDP reply arrived back before the receive() call was made and the rx socket set up. You could make sure by raising the priority of the receive thread, (or lowering the priority of the send thread).
You could wait on another semaphore after the send() and signal it after the receive(), so ensuring that the send thread does not attempt to send again until the rx is done. Not sure how you would detect comms failures, IIRC, Java semaphore waits do not have a timeout :((
Rgds,
Martin