15

I'm planning to use an instance of DatagramSocket and call its send method from different threads... to send UDP packets to different clients. Is the method thread safe i.e. calling this method from different threads will not create any trouble/inconsistency/race condition?

Thanks!

Shafiul
  • 2,832
  • 9
  • 37
  • 55

3 Answers3

9

Yes. This is only a thin layer on the native OS, which is threadsafe.

See here http://www.velocityreviews.com/forums/t150685-is-datagramsocket-thread-safe.html

BraveNewCurrency
  • 12,654
  • 2
  • 42
  • 50
9

UDP guarantees that datagrams arrive intact (if at all). In other words there can be no interleaving even if there is multithreading at the sender. That's all you need. You don't actually need thread safety. However the C send() system call is thread safe, like all system calls, because they are atomic.

user207421
  • 305,947
  • 44
  • 307
  • 483
  • 6
    But is it really guarantees that java wrapper will be thread safe? I think - no. – turbanoff Mar 24 '15 at 11:12
  • @turbanoff It's irrelevant whether the wrapper is thread-safe or not, as it isn't specified to change any state in any objects. – user207421 Feb 19 '16 at 07:50
  • 3
    I don't get your argument. For example, SimpleDateFormat isn't specified to changed any state in any objects. But everybody know - it isn't thread-safe. – turbanoff Feb 19 '16 at 09:19
  • @turbanoff So it changes state in itself. Otherwise it would be threadsafe. By definition. – user207421 Jan 09 '17 at 23:23
1

The answer is yes, the layer on the native operating system is thread safe.

BUT, because network throughput is limited, if you send more packets than the network can handle, some packets will be dropped.

Greelings
  • 4,964
  • 7
  • 34
  • 70
  • So......... is it threadsafe or not? There are contradicting answers in this very answer section. – Aung Khant Feb 01 '22 at 01:55
  • Yes, it is thread safe. However, because network throughput is limited, if you send more packets than the network can handle, some packets will be dropped. But that has nothing to do with multithreading. Well, not directly. – Greelings Feb 01 '22 at 11:54