Problem with ExecutorService

2

I'm doing a project in which I'm going to do a large number of operations that can be done simultaneously, so I thought about creating threads.

These operations will give a result that I want to store in a list so that when they finish executing the threads, I can process those results.

The problem that I am having with the code that I will put next, is that I am doing tests with a size of 320 pcs in the list of todosPC , but the list of results resultados is returning me a variable lower number , that is, some executions tell me that there are 317 results and others 319.

It does not occur to me that it could be the cause of this problem, any suggestions?

Next I put the code that 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)));  
            }
        }
    });
 }
    
asked by Joacer 26.05.2017 в 13:22
source

1 answer

3

I solved my problem, the problem was that the result list was being accessed concurrently.

To solve it, it was enough to use synchronizedList :

private static List<ResTelnetDto> resultados = Collections.synchronizedList(new ArrayList<ResTelnetDto>());
    
answered by 26.05.2017 / 15:01
source