Java同步写块
我是java新手,我有一个关于同步的问题。
我有以下用于写入网络的代码(现在简单实现):
public void networkSendData(byte[] data){
try {
out.write(data);
out.flush();
} catch (IOException e) {
}
}
我想知道是否需要在这里进行块级同步,因为我正在一次写入整个数据。或者有可能出现竞争条件吗?我问这个问题是因为要写入的数据来自多个来源。
谢谢。
im new to java and i have a question regarding Synchronized.
i have the following code for writing to network (simple implementation for now):
public void networkSendData(byte[] data){
try {
out.write(data);
out.flush();
} catch (IOException e) {
}
}
i was wondering if there is a need for block level Synchronized here as im am writing the whole data at once. or is there a chance for race condition? i ask because the data to write is coming for multiple sources.
thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在您的示例中,除非多个线程要访问同一
out
变量,否则不需要 Synchronize 块。换句话说,如果您有多个线程同时调用
networkSendData
,则应该同步
该方法。您不希望一个线程调用flush
,而另一个线程正在执行write
方法。您还需要确保没有线程正在访问/修改
out
变量的值,而另一个线程可能位于networkSendData
方法中。这取决于接收写入数据的服务器如何处理它。如果使用多个线程根据写入服务器的内容来更新共享可变变量,则需要实现线程安全。With your example, there is no need to have a
synchronize
d block unless multiple threads are going to have access to the sameout
variable.In other words, if you have multiple threads all calling
networkSendData
at the same time, you shouldsynchronize
the method. You do not want to have one thread callingflush
while another thread is half way through executing thewrite
method.You will also need to make sure that no threads are accessing/modifying the value of the
out
variable while there is a chance that another thread can be in thenetworkSendData
method.This depends on how the server that is receiving the written data handles it. If multiple threads are used to update a shared mutable variable based on what is written to the server, you will need to implement thread safety.