开发者

Java Synchronized Write Block

开发者 https://www.devze.com 2022-12-30 12:15 出处:网络
im new to java and i have a question regarding Synchronized. i have the following code for writing to network (simple implementation for now):

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 chan开发者_Python百科ce for race condition? i ask because the data to write is coming for multiple sources.

thank you.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消