开发者

Is Java MulticastSocket threadsafe?

开发者 https://www.devze.com 2023-01-04 09:33 出处:网络
I have two threads. First one sends datagrams with a MulticastSocket in loop;开发者_StackOverflow社区 the second thread receives datagrams using the same instance of MulticastSocket in loop.

I have two threads. First one sends datagrams with a MulticastSocket in loop;开发者_StackOverflow社区 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?


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消