Skip to content
Advertisement

SocketChannel: Single or multi , which is better?

SocketChannel is thread safe, so only one channel is need for communication between client and server. the channel served for read/write operations simultaneously

But, if we using multi channels (more than one connections between the same client and server), will the io performance be improved ???

If can, why??????

any answer is welcome.

Suppose a cache client, which poll data from remote server.

public class Client(){
    public Object getThroungOneChannel(Object key){
       getTheUniqueChannel().write(request);
       waitForResponse();
    }

    public Object getWithMultiChannel(Object key){
       getChannelFromAPool().write(request)
       waitForResponse();
    }
}

which way will have better io performance.

Advertisement

Answer

In general, a single connection between a client and server is the best way to go. I can’t imagine how multiple connections to transfer same data between same client and server could help. With a proper implementation of command-pattern, you could optimize the usage of the channel to max, in fact that’s the whole advantage of NIO. For e.g., suppose even if you have a thread writing to a channel blocked producing data, you could have another thread writing some other data to the same channel, but you have to code smartly to extract the best out of NIO.

And for your given example, I believe, in trivial cases the getThroungOneChannel() will outperform getWithMultiChannel()

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement