user1620902
user1620902

Reputation: 81

Atomic socket messages across multiple sockets

I have a couple questions about socket programming in Java.

  1. I have a process that needs to send one message across multiple socket connections. Right now I have this as follows

    Socket[] connections; //Already initialized with all connections
    
    for i=0 to connections.length - 1
        Send Message across connection[i]; // a new PrintWriter linked to the output stream
    

    Is that as atomic as this broadcast could be? Or is there potential in a concurrent environment they may not all be sent at the nearly same instant?

  2. In a concurrent environment are the output streams to socket connections (set up as a PrintWriter) already mutually exclusive? Say, two threads want to simultaneously write to the PrintWriter. Will any of the output to the stream be messed up without explicit mutual exclusion on the PrintWriter?

Upvotes: 0

Views: 397

Answers (1)

Gray
Gray

Reputation: 116878

Is that as atomic as this broadcast could be? Or is there potential in a concurrent environment they may not all be sent at the nearly same instant?

Not sure what you are asking here. Multiple thread cannot use a Socket object at the same time. You will need to synchronize around the socket object if it is being accessed concurrently.

If you are asking if all of the messages will be sent by a single thread "at the same time" then the answer is "it depends". A single thread can do this quickly but if any of the send operations block for any reason, then it might not. It depends highly on the size of the messages and how often the sockets are written to.

In a concurrent environment are the output streams to socket connections (set up as a PrintWriter) already mutually exclusive?

If you look at the PrintWriter code, you can see that all operations are synchronized. This means that concurrent writing to a socket from a PrintWriter should be fine. For example:

public void println(int x) {
    synchronized (lock) {
        print(x);
        println();
    }
}

Upvotes: 1

Related Questions