views:

50

answers:

1

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.

+1  A: 

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.

Finbarr
on the server-side there is only one thread listending for incoming data.
iEisenhower
I have updated my answer.
Finbarr
thanks that is what i was wondering. multiple nodes transmitting at the same time (rare but could happen).
iEisenhower