How to continue a for loop after a certain time without using `try ... catch` method?

112 views Asked by At
new Thread(new Runnable() {
    @Override
    public void run() {
        List<Socket> socketList = new ArrayList<>();
        for (String ip: iplist) {
            Socket socket = null;
            try {
                socket = new Socket(ip,23);
            } catch (IOException e) {
                e.printStackTrace();
            }
            socketList.add(socket);
        }
    }
}).start();

I am trying to make a new socket for each ip in a iplist and adding that socket to a list of sockets. I am using a for loop for this. When using try ... catch , the loop execution is paused for some long time when socket connection fails. So I need a better alternative to know that socket connection is failed and make the loop continue its execution by adding a null socket to the list of sockets.

1

There are 1 answers

2
janos On BEST ANSWER

You could do this:

  • Use a separate thread for the creation of each socket.
  • Use a concurrent collection (instead of List) to store the sockets, for example ConcurrentLinkedDeque.
  • Wait for all of the socket creator threads to complete, and then add all elements of the concurrent list to the normal List, if needed. You could implement this using for example a CompletionService.

With this approach, sockets that fail would still take a long time, but would not block the creation of other sockets. If you can run one thread per socket, than the maximum time used to create all sockets will be close the time of a single failure.

By waiting until all sockets are created, the implementation would not be a logical departure from your current solution, it would just be faster, and the complexity would be self-contained.

Another alternative is to not wait until all sockets are created, and let all socket creations complete in their threads. That would be a significant departure from the current implementation, and the complexity of handling the socket creation threads affecting the code outside of your method.