I am carrying out a project in which I am going to carry out a large number of operations that can be carried out simultaneously, for this reason I have thought about creating threads.
These operations will give a result that I want to store in a list so that when the threads are finished executing, I can process those results.
The problem that I am having with the code that I will put next, is that I am testing with a size of 320 pcs in the list of todosPC
, but the list of results resultados
is returning a variable lower number, that is, that some executions make me There are 317 results and 319 others.
I can't think of what might be causing this problem, any suggestions?
Here is the code I have:
private static final int TELNET_SIZE = 50;
private static final long TIMEOUT_WAIT_EXECUTION = 60;
private static ExecutorService threadPool = null;
private static List<ResTelnetDto> resultados = new ArrayList<ResTelnetDto>();
public static void main( String[] args )
{
List<PCDto> todosPC = getAllPcs();
int total = todosPC.size();
//Calculamos el número de hilos a crear
if(total > TELNET_SIZE){
hilos = total/TELNET_SIZE ;
if((total % TELNET_SIZE) > 0 ){
hilos++;
}
}else if(total >0){
hilos++;
}
threadPool = Executors.newFixedThreadPool(hilos);
for(PCDto pc : todosPC){
pcParciales.add(pc);
int partialSize = pcParciales.size();
//repartimos los pcs en cada hilo
if (partialSize == TELNET_SIZE || counter == total) {
//se abre el hilo para que realice las operaciones
comprobarPCs(pcParciales);
pcParciales.clear();
}
}
threadPool.shutdown();
threadPool.awaitTermination(TIMEOUT_WAIT_EXECUTION, TimeUnit.SECONDS);
logApp.info("Todas las tareas terminadas! resultados: " + resultados.size());
}
public static void comprobarPCs(final List<PCDto> pcParciales){
final List<PCDto> pcs = new ArrayList<PCDto>(pcParciales);
threadPool.execute(new Runnable() {
public void run() {
for(PCDto pc : pcs){
boolean res = telnet(pc.getNombre(), pc.getPuertos());
resultados.add(new ResTelnetDto(pc.getId(), ((res)?1:0)));
}
}
});
}
I have solved my problem, the problem was that the result list was being accessed concurrently.
To solve it, it was enough to use synchronizedList :