Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Java socket multi-thread safe?

If I have multiple Java threads writing to the same Socket instance simultaneously, will that affect the integrity of the objects that are read from the same socket? I.e., whether the contents of the objects will be messed up etc. It's fine for the ordering of objects to be random.

like image 970
JRR Avatar asked Nov 24 '12 21:11

JRR


People also ask

Are Java sockets thread safe?

Sockets are thread unsafe at the stream level. You have to provide synchronization. The only warranty is that you won't get copies of the exact same bytes in different read invocations no matter concurrency.

Are sockets thread safe?

Sockets are not part of C++ Standard so it depends on implementation. Generally they are not thread safe since send is not an atomic operation.

Is multi threading safe?

A MessageService object is effectively immutable since its state can't change after its construction. So, it's thread-safe. Moreover, if MessageService were actually mutable, but multiple threads only have read-only access to it, it's thread-safe as well.

Can multiple threads write to the same socket?

Indeed your design does allows several Threads to obtain the same Socket handle.


1 Answers

In general, there are no guarantees. Bits of different objects could well end up getting interleaved on the wire, rendering the result indecipherable. Therefore, you need to provide external synchronization.

It is interesting to note that even a single socket write at the OS level is not necessarily atomic. For further discussion, see Is it safe to issue blocking write() calls on the same TCP socket from multiple threads? and Be careful with the sendmsg() family of functions.

like image 61
NPE Avatar answered Oct 13 '22 00:10

NPE