Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Java MulticastSocket threadsafe?

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?

like image 958
Lopotun Avatar asked Jun 24 '10 09:06

Lopotun


2 Answers

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.

like image 199
Boris Pavlović Avatar answered Sep 28 '22 08:09

Boris Pavlović


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.

like image 42
Vicente Reig Avatar answered Sep 28 '22 09:09

Vicente Reig