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.
With your example, there is no need to have a
synchronized block unless multiple threads are going to have access to the sameoutvariable.In other words, if you have multiple threads all calling
networkSendDataat the same time, you shouldsynchronizethe method. You do not want to have one thread callingflushwhile another thread is half way through executing thewritemethod.You will also need to make sure that no threads are accessing/modifying the value of the
outvariable while there is a chance that another thread can be in thenetworkSendDatamethod.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.