Java套接字多线程安全吗? [英] Is Java socket multi-thread safe?

查看:465
本文介绍了Java套接字多线程安全吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有多个Java线程同时写入同一个Socket实例,会影响从同一个套接字读取的对象的完整性吗?即,对象的内容是否会被弄乱等等。对象的排序是随机的。

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.

推荐答案

一般来说,没有任何保证。不同对象的比特很可能最终在线上交错,使结果难以辨认。 因此,您需要提供外部同步。

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.

值得注意的是,即使在操作系统级别进行单个套接字写入也不一定是原子的。有关进一步的讨论,请参阅在多个线程的同一TCP套接字上发出阻塞write()调用是否安全?小心sendmsg()系列函数

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.

这篇关于Java套接字多线程安全吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆