I was reasoning about multicast socket thread-safety in my application. First of all I've multiple threads sharing the same multicast socket instance, this multicast socket is used to join different groups on the same port. Here are my questions:
- Do I have to synchronize calls to
joinGroup()
andleaveGroup()
methods? - Do I have to synchronize calls to
send()
andreceive()
methods which uses always new istance of datagram packet as parameter?
Here's a code example of the 2nd question:
/* SEND METHOD EXAMPLE. */
DatagramPacket sndPckt = new DatagramPacket(buf, buf.length, groupAddr,port);
try{
multicastSocket.send(sndPckt);
} catch (IOException e) {
/* Error handling. */
}
/* RECEIVE METHOD EXAMPLE. */
DatagramPacket recv = new DatagramPacket(buf, buf.length);
try{
multicastSocket.receive(recv);
} catch (IOException e) {
/* Error handling. */
}
I've found this answer but it talks about using the sameDatagram Packet
.
I've also tested my application but I didn't found any race condition or inconsistency but I'm not 100% sure that there usage is thread-safe.