So I have this piece of code I want to optimize. The idea of the program is to iterate a list of hosts and then create one thread per host and connect to it via SSH to validate some things and then save the results in an object.
Right now the code takes a long time (20 minutes) to run through 8000 hosts. I want to optimize this code to fully maximize the utilization of CPU, cores and memory and hopefully finish faster.
ConcurrentLinkedQueue<Host> hosts= new ConcurrentLinkedQueue<Host>();
List<FutureTask<Host>> taskList = new ArrayList<FutureTask<Host>>();
final int cpus = Runtime.getRuntime().availableProcessors();
int threadCount = 1000;
if(cpus <= 2){
threadCount = cpus * 4;
}
ExecutorService executor = Executors.newFixedThreadPool(threadCount);
for (String resource : resources) {
FutureTask<Host> task = new FutureTask<Host>(new Worker(resource);
taskList.add(task);
executor.submit(task);
}
System.out.println("Processing... Waiting for all threads to finish...");
for (int j = 0; j < taskList.size(); j++) {
FutureTask<Host> futureTask = taskList.get(j);
try {
hosts.add(futureTask.get());
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
executor.shutdown();