javaudpmulticastmulticastsocket

Do I need to put some sort of mutual exclusion while multiple threads are writing on the same MulticastSocket?


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?


Solution

  • 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(/*...*/);
    }