Question

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.

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top