0

For now I have sequential single threaded algorithm like this:

boolean conn = false;

for (InetSocketAddress addr : addrs) {
    while (!conn) {
        SocketChannel ch = SocketChannel.open();
        ch.configureBlocking(true);
        ch.socket().setTcpNoDelay(tcpNoDelay);
        ch.socket().setKeepAlive(true);

        try {
            ch.socket().connect(addr, connTimeout);
            conn = true;
            ....
        }
        catch (...) {
           log("Not available: " + addr);
        }

        if (conn) 
         break;
    }
}

But in some situations I could have quite a large list of addresses and available address could be in the end of this list - this will result into slow discovery of available address because I need to check all addresses one by one.

So my question - how I could implement algorithm that will try to connect to several addresses from different threads and will exit once first available address is found?

Also this algorithm should exit if no address available.

Any ideas how to code this?

karthik manchala
  • 13,492
  • 1
  • 31
  • 55
kuaw26
  • 456
  • 2
  • 10

1 Answers1

0

Do all the connects in non-blocking mode, and then use a Selector on OP_CONNECT to find out when and if the connections succeed.

user207421
  • 305,947
  • 44
  • 307
  • 483
  • do you mean that all my "100" addresses will be connected in case they are all available? I need only first successful – kuaw26 Apr 05 '16 at 10:31
  • That's correct. You can't find out whether you can connect without trying to connect. Alternatively you could try shortening the timeout. – user207421 Apr 05 '16 at 10:39
  • @kuaw26, either you want the first - than you have to do it sequentially - or you want 'any of the available' - than do non-blocking. Pick one. – SergeyA Apr 05 '16 at 13:03
  • @SergeyA, why? It is possible to have small thread pool (2-3 threads) that will try to connect to 3 addresses in parallel all other addresses will be in queue. Once any of threads successfully connected - it will stop thread pool and cleanup queue. Will this work? – kuaw26 Apr 05 '16 at 16:20
  • 1
    Than you will have a random selection of first 3 available addressess. – SergeyA Apr 05 '16 at 16:23
  • @SergeyA, for my task it is OK to be connected to any available address. I thinking about such approach because I'm afraid that if I will use non blocking mode and connect to all my "100" addresses at once this will lead to huge network utilization. – kuaw26 Apr 06 '16 at 00:42