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.
You could do this:
List
) to store the sockets, for exampleConcurrentLinkedDeque
.List
, if needed. You could implement this using for example aCompletionService
.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.