views:

122

answers:

2

I have two threads. First one sends datagrams with a MulticastSocket in loop; the second thread receives datagrams using the same instance of MulticastSocket in loop.

It seems to be working properly, but I'm still in doubts.

Can these two threads use the same instance of MulticastSocket? Is MulticastSocket threadsafe in respect send/receive methods invocation?

+1  A: 

DatagramSocket is thread safe, what leds me to think that MulticastSocket is thread safe too, as long as it is a derivative class.

Vicente Reig
Well, the link indeed says that DatagramSocket is threadsafe. However, I cannot confirm it looking at DatagramSocket source.
Lopotun
Just as Boris pointed below, at DatagramSocket#send lines 574-6 you can see that send(DatagramPacket) is synchronized over its argument, while the whole DatagramSocket#receive method is marked as synchronized.
Vicente Reig
+1  A: 

Both send and receive DatagramPacket methods are synchronized on the sending/receiving datagram packet. In other words if you are using a same datagram packet to send and receive from two different threads these two methods will be synchronized as they are going to use the same object as a synchronization token.

It's much easier to understand once looked at the source code of DatagramSocket.

Boris Pavlović
That's all. If I use the same instance of DatagramPacket then I cannot send and receive the DatagramPacket simultaneously from two different threads.
Lopotun
No, you are not able to simultaneously send and receive the same instance of DatagramPacket from two different threads.
Boris Pavlović