Java同步写块

发布于 2024-09-02 05:18:22 字数 314 浏览 0 评论 0原文

我是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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

累赘 2024-09-09 05:18:22

在您的示例中,除非多个线程要访问同一 out 变量,否则不需要 Synchronize 块。

换句话说,如果您有多个线程同时调用networkSendData,则应该同步该方法。您不希望一个线程调用 flush,而另一个线程正在执行 write 方法。

public synchronized void networkSendData(byte[] data)

您还需要确保没有线程正在访问/修改 out 变量的值,而另一个线程可能位于 networkSendData 方法中。

这取决于接收写入数据的服务器如何处理它。如果使用多个线程根据写入服务器的内容来更新共享可变变量,则需要实现线程安全。

With your example, there is no need to have a synchronized block unless multiple threads are going to have access to the same out variable.

In other words, if you have multiple threads all calling networkSendData at the same time, you should synchronize the method. You do not want to have one thread calling flush while another thread is half way through executing the write method.

public synchronized void networkSendData(byte[] data)

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 the networkSendData 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文