6

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?

Lopotun
  • 611
  • 7
  • 15

2 Answers2

6

Both send and receive DatagramSocket 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.

user207421
  • 305,947
  • 44
  • 307
  • 483
Boris Pavlović
  • 63,078
  • 28
  • 122
  • 148
  • 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 Jun 24 '10 at 09:52
  • No, you are not able to simultaneously send and receive the same instance of DatagramPacket from two different threads. – Boris Pavlović Jun 24 '10 at 11:11
2

DatagramSocket is thread safe, MulticastSocket is a derivative class, in consequence MulticastSocket.send is thread-safe, since access is being serialized by a synchronized block.

Vicente Reig
  • 877
  • 9
  • 14
  • Well, the link indeed says that DatagramSocket is threadsafe. However, I cannot confirm it looking at DatagramSocket source. – Lopotun Jun 24 '10 at 09:47
  • 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 Jun 24 '10 at 10:12
  • Th link above is merely a copy of posts that were originally made in the Sun Java forums. – user207421 May 30 '15 at 19:02
  • Good catch, changed the link to point to the `DatagramSocket` source as it was doing 5 years ago. – Vicente Reig May 31 '15 at 23:20