2

I have some threads which are writing on the same MulticastSocket (depending by the scheduling, probably can happen than more then one thread is writing on the MulticastSocket at the same time). Do I have to get them write on it one per timer by using some form of locking, or the UDP protocol is doing this implicitly?

  • No. UDP datagrams are atomic, system calls are atomic, and `DatagramSocketImpl.send()` is synchronized. – user207421 Oct 25 '19 at 09:45
  • @user207421 - I don't see anything saying `send` is synchronized in the documentation [here](https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/net/MulticastSocket.html#send(java.net.DatagramPacket,byte)) or [here](https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/net/DatagramSocket.html#send(java.net.DatagramPacket)). Where can I find that? Remember that **implementations** can change, you have to program to the **contract**. – T.J. Crowder Oct 25 '19 at 09:47
  • Now I'm a bite confused. Should I put an explicit lock according or not, like @user207421 says? – Alexandra Bradan Oct 25 '19 at 09:55
  • @AlexandraBradan - user207421 is referring to a specific implementation of `MulticastSocket` that (I guess, from his comment) uses `DatagramSocketImpl.send()`. You program to *contract*, not implementation. The contract doesn't say it's threadsafe, so you have to assume it isn't. Doing otherwise is poor practice and asking for trouble. If your code runs on a different JDK that implements it differently (either a different vendor's JDK, or a different version of the same vendor's JDK), the implementation can be different. – T.J. Crowder Oct 25 '19 at 10:09

1 Answers1

1

It doesn't really have anything to do with UDP. The documentation for MulticastSocket doesn't say it's threadsafe, so you can't assume it's threadsafe. You can't know that it doesn't update internal structures (such as an outbound buffer) which could be damaged by simultaneous access.

If all the threads are using the same instance of MulticastSaocket, you'll want to ensure they don't simultaneously call its methods. You can do that easily enough by synchronizing on the instance:

synchronized (theSocket) {
    theSocket.send(/*...*/);
}
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875