SlideShare a Scribd company logo
FACILITANDO A
                      PROGRAMAÇÃO
                    CONCORRENTE COM O
                         FORK/JOIN
                           Mário Amaral
                            @mario_fts
Thursday, December 6, 12
QUE MÁRIO?




Thursday, December 6, 12
QUE MÁRIO?

   • Desenvolvedor         Java desde 2004




Thursday, December 6, 12
QUE MÁRIO?

   • Desenvolvedor              Java desde 2004

   • Instrutor             na Caelum




Thursday, December 6, 12
QUE MÁRIO?

   • Desenvolvedor              Java desde 2004

   • Instrutor             na Caelum

   • Caelum-Stella




Thursday, December 6, 12
QUE MÁRIO?

   • Desenvolvedor              Java desde 2004

   • Instrutor             na Caelum

   • Caelum-Stella

   • Personagem              de games desde 1981




Thursday, December 6, 12
VAMOS FALAR DE
                             PARALELISMO
Thursday, December 6, 12
POR QUE PARALELIZAR



    • Ganhar               tempo




Thursday, December 6, 12
POR QUE PARALELIZAR
    • Aproveitar           recursos ociosos




Thursday, December 6, 12
O QUE PARALELIZAR?




Thursday, December 6, 12
O QUE PARALELIZAR?


    • Tarefas              Independentes com processamento pesado




Thursday, December 6, 12
O QUE PARALELIZAR?


    • Tarefas              Independentes com processamento pesado

         • Processar           mensagens de uma fila




Thursday, December 6, 12
O QUE PARALELIZAR?


    • Tarefas              Independentes com processamento pesado

         • Processar           mensagens de uma fila

         • Conversão            de dados




Thursday, December 6, 12
O QUE PARALELIZAR?


    • Tarefas              Independentes com processamento pesado

         • Processar           mensagens de uma fila

         • Conversão            de dados

         • Aplicar          filtros em imagens



Thursday, December 6, 12
O PROBLEMA




Thursday, December 6, 12
O PROBLEMA


    • Conversão            de dados




Thursday, December 6, 12
O PROBLEMA


    • Conversão               de dados

    • Dados                de vendas




Thursday, December 6, 12
O PROBLEMA


    • Conversão               de dados

    • Dados                de vendas

    • CSV           => JSON




Thursday, December 6, 12
OS DADOS




Thursday, December 6, 12
OS DADOS
                           • 1;1;04122012;fichario   preto;9;33.55




Thursday, December 6, 12
OS DADOS
                           • 1;1;04122012;fichario   preto;9;33.55




Thursday, December 6, 12
OS DADOS
                           • 1;1;04122012;fichario   preto;9;33.55




                             {
                                 "number": 1,
                                 "terminal": 1,
                                 "description": "fichario preto",
                                 "price": 33.55,
                                 "date": "04122012"
                             }
Thursday, December 6, 12
PASSO A PASSO


    • Ler         os dados do CSV e converter para objetos.

    • Para          cada objeto, converter em Json.

    • Adicionar              o Json em uma lista de String.

    • Gravar               o conteúdo da lista em um arquivo.



Thursday, December 6, 12
SINGLE THREAD



    • Processar            tudo sequencialmente em um loop

    • Implementação             mais simples




Thursday, December 6, 12
CÓDIGO....
	 public List<String> toJson(List<?> list) {
	 	 List<String> lines = new ArrayList<>();
	 	 for (Object value : list) {
	 	 	 lines.add(new JsonObject(value)
                            .toString());
	 	 }
	 	 return lines;
	 }



Thursday, December 6, 12
TESTANDO


    •1       milhão de registros

    • Executar               10 vezes seguidas cada método.

    • Desconsiderar               o menor e o maior tempo.

    • Obter                o tempo médio.



Thursday, December 6, 12
TEMPO

                                     Tempo
                           Método
                                    Médio (ms)


                           Single      5562




Thursday, December 6, 12
MULTI THREAD




Thursday, December 6, 12
MULTI THREAD


    • Cada            conversão é independente da outra.




Thursday, December 6, 12
MULTI THREAD


    • Cada            conversão é independente da outra.

    •    Múltiplos processadores




Thursday, December 6, 12
MULTI THREAD


    • Cada            conversão é independente da outra.

    •    Múltiplos processadores

    • Dividir              e distribuir!




Thursday, December 6, 12
threads.add(createANewThread(sales, jsons,
      	 	 	 	 	 	 	 	 	 	 	 	 	 	 beginIndex,finalIndex));




Thursday, December 6, 12
threads.add(createANewThread(sales, jsons,
      	     	     	        	 	 	 	 	 	 	 	 	 	 	 beginIndex,finalIndex));
      	     	     	        beginIndex = finalIndex;
      	     	     	        finalIndex = finalIndex + amount >= size ?
                                          size	:
                                          finalIndex + amount;




Thursday, December 6, 12
while                (true) {
      	 	 	                threads.add(createANewThread(sales, jsons,
      	 	 	                	 	 	 	 	 	 	 	 	 	 	 beginIndex,finalIndex));
      	 	 	                beginIndex = finalIndex;
      	 	 	                finalIndex = finalIndex + amount >= size ?
                                          size	:
                                          finalIndex + amount;




      }



Thursday, December 6, 12
while                (true) {
      	 	 	                threads.add(createANewThread(sales, jsons,
      	 	 	                	 	 	 	 	 	 	 	 	 	 	 beginIndex,finalIndex));
      	 	 	                beginIndex = finalIndex;
      	 	 	                finalIndex = finalIndex + amount >= size ?
                                          size	:
                                          finalIndex + amount;

      	 	 	 if (beginIndex == size) {
      	 	 	 	 break;
      	 	 	 }
      }



Thursday, December 6, 12
protected List<String> convertToJson(List<Sale> sales){
...

      while                (true) {
      	 	 	                threads.add(createANewThread(sales, jsons,
      	 	 	                	 	 	 	 	 	 	 	 	 	 	 beginIndex,finalIndex));
      	 	 	                beginIndex = finalIndex;
      	 	 	                finalIndex = finalIndex + amount >= size ?
                                          size	:
                                          finalIndex + amount;

      	 	 	 if (beginIndex == size) {
      	 	 	 	 break;
      	 	 	 }
      }
}

Thursday, December 6, 12
protected List<String> convertToJson(List<Sale> sales){

	     	     int size = sales.size();
	     	
	     	     int amount = size / NUMBER_OF_THREADS; //4
	     	     int beginIndex = 0;
	     	     int finalIndex = amount;

	 	 List<Thread> threads = new ArrayList<>();
	 	 List<String> jsons = Collections.synchronizedList(
                              new ArrayList<String>());

	 	 while (true) {
      //Cria uma nova thread para cada parte
	 	 }


Thursday, December 6, 12
protected List<String> convertToJson(List<Sale> sales){

 	     	     ...
 	     	
 	     	     for (Thread thread : threads) {
 	     	     	 thread.start();
 	     	     }

 	 	
 	 	
 	 	

 	 	 return jsons;

 	 }


Thursday, December 6, 12
protected List<String> convertToJson(List<Sale> sales){

 	     	     ...
 	     	
 	     	     for (Thread thread : threads) {
 	     	     	 thread.start();
 	     	     }

 	 	 for (Thread thread : threads) {
 	 	 	 thread.join();
 	 	 }

 	 	 return jsons;

 	 }


Thursday, December 6, 12
@Override
	    protected List<String> convertToJson(List<Sale> vendas) throws Exception {

	    	     System.out.println("Convert to json....");

	    	     int size = vendas.size();
	    	
	    	     int amount = size / NUMBER_OF_THREADS; //4
	    	     int beginIndex = 0;
	    	     int finalIndex = amount;

	    	     List<Thread> threads = new ArrayList<>();
	    	     List<String> jsons = Collections.synchronizedList(new ArrayList<String>());

	    	     while (true) {
	    	     	   threads.add(createANewThread(vendas, jsons, beginIndex, finalIndex));
	    	     	   beginIndex = finalIndex;
	    	     	   finalIndex = finalIndex + amount >= size ? size	: finalIndex + amount;

	    	     	     if (beginIndex == size) {
	    	     	     	   break;
	    	     	     }
	    	     	
	    	     }

	    	     for (Thread thread : threads) {
	    	     	   thread.start();
	    	     }

	    	     for (Thread thread : threads) {
	    	     	   thread.join();
	    	     }

	    	     System.out.println("Finished!n	");
	    	     return jsons;

	    }
Thursday, December 6, 12
TEMPO
                                           Tempo
                             Método
                                          Médio (ms)

                              Single         5562


                           Multi Thread      3739




Thursday, December 6, 12
COMPARATIVO
                                  Single      Multi Thread

                           6000



                           4000



                           2000


                                    5562           3739
                              0
                                           Tempo


Thursday, December 6, 12
DIFICULDADES




Thursday, December 6, 12
DIFICULDADES


    • Decidir              a quantidade de Threads




Thursday, December 6, 12
DIFICULDADES


    • Decidir              a quantidade de Threads

    • Dividir              o trabalho




Thursday, December 6, 12
DIFICULDADES


    • Decidir               a quantidade de Threads

    • Dividir              o trabalho

    • Juntar               tudo no final




Thursday, December 6, 12
protected List<String> convertToJson(List<Sale> sales){

	     	     int size = sales.size();
	     	
	     	     int amount = size / NUMBER_OF_THREADS; //4
	     	     int beginIndex = 0;
	     	     int finalIndex = amount;

	 	 List<Thread> threads = new ArrayList<>();
	 	 List<String> jsons = Collections.synchronizedList(
                              new ArrayList<String>());

	 	 while (true) {
      //Cria uma nova thread para cada parte
	 	 }


Thursday, December 6, 12
FORK / JOIN




Thursday, December 6, 12
FORK / JOIN


    • Java         7




Thursday, December 6, 12
FORK / JOIN


    • Java         7

    • Dividir              tarefas entre múltiplos processadores




Thursday, December 6, 12
FORK / JOIN


    • Java         7

    • Dividir              tarefas entre múltiplos processadores

    • Tarefas              que podem ser quebradas recursivamente




Thursday, December 6, 12
COMO FUNCIONA
    class ExemploForkJoin extends RecursiveTask<Long>{

    	 @Override
    	 protected Long compute() {

    	     	     if(qtdeDeDados < LIMITE){
    	     	     	 // execute a tarefa
    	     	     }else{
    	     	     	 //Divida o trabalho entre subtarefas
    	     	     	 //Execute as subtarefas e espere o resultado
    	     	     }
    	     }
    }

Thursday, December 6, 12
COMO FUNCIONA




Thursday, December 6, 12
COMO FUNCIONA




Thursday, December 6, 12
COMO FUNCIONA




Thursday, December 6, 12
COMO FUNCIONA




Thursday, December 6, 12
COMO FUNCIONA


                              fork()




Thursday, December 6, 12
COMO FUNCIONA


                              fork()   fork()




Thursday, December 6, 12
COMO FUNCIONA


                              fork()   fork()




Thursday, December 6, 12
COMO FUNCIONA


                              fork()   fork()




Thursday, December 6, 12
COMO FUNCIONA


                              fork()   fork()




Thursday, December 6, 12
COMO FUNCIONA


                              fork()   fork()




Thursday, December 6, 12
COMO FUNCIONA


                              fork()   fork()




Thursday, December 6, 12
COMO FUNCIONA


                              fork()   fork()




Thursday, December 6, 12
COMO FUNCIONA


                                    fork()   fork()




                           join()




Thursday, December 6, 12
COMO FUNCIONA


                                    fork()    fork()




                           join()    join()




Thursday, December 6, 12
COMO FUNCIONA


                                    fork()    fork()




                           join()    join()




Thursday, December 6, 12
COMO FUNCIONA

                                    join()

                                             fork()    fork()




                           join()             join()




Thursday, December 6, 12
COMO FUNCIONA

                                    join()                      join()

                                             fork()    fork()




                           join()             join()




Thursday, December 6, 12
IMPLEMENTANDO
  public class JsonTask extends 	 	
  	 	 	 	 	 	 	 	 	 	    RecursiveTask<List<String>>{

  	 private final int THRESHOLD = 10000;
  	 private List<Sale> list;
  	
  	 //constructor...

  	     @Override
  	     protected List<String> compute() {
  	     	
  	     }
  }
Thursday, December 6, 12
IMPLEMENTANDO
  public class JsonTask extends 	 	
  	 	 	 	 	 	 	 	 	 	    RecursiveTask<List<String>>{

  	 private final int THRESHOLD = 10000;
  	 private List<Sale> list;
  	
  	 //constructor...

  	     @Override
  	     protected List<String> compute() {
  	     	
  	     }
  }
Thursday, December 6, 12
IMPLEMENTANDO
  public class JsonTask extends 	 	
  	 	 	 	 	 	 	 	 	 	    RecursiveTask<List<String>>{

  	 private final int THRESHOLD = 10000;
  	 private List<Sale> list;
  	
  	 //constructor...

  	     @Override
  	     protected List<String> compute() {
  	     	
  	     }
  }
Thursday, December 6, 12
IMPLEMENTANDO
  public class JsonTask extends 	 	
  	 	 	 	 	 	 	 	 	 	    RecursiveTask<List<String>>{

  	 private final int THRESHOLD = 10000;
  	 private List<Sale> list;
  	
  	 //constructor...

  	     @Override
  	     protected List<String> compute() {
  	     	
  	     }
  }
Thursday, December 6, 12
@Override
protected List<String> compute() {	
	    List<String> jsons = new ArrayList<>();
     int size = list.size();
	             if ( size < THRESHOLD){
	 	              jsons.addAll(new JsonMapper().toJson(list));
              }else{
                ...
              }
              return jsons;
}




Thursday, December 6, 12
}else{




}



Thursday, December 6, 12
}else{

     JsonTask left =
                new JsonTask(list.subList(0, size / 2));




}



Thursday, December 6, 12
}else{

     JsonTask left =
                new JsonTask(list.subList(0, size / 2));

     JsonTask right =
                new JsonTask(list.subList(size / 2, size));




}



Thursday, December 6, 12
}else{

     JsonTask left =
                new JsonTask(list.subList(0, size / 2));

     JsonTask right =
                new JsonTask(list.subList(size / 2, size));

     left.fork();




}



Thursday, December 6, 12
}else{

     JsonTask left =
                new JsonTask(list.subList(0, size / 2));

     JsonTask right =
                new JsonTask(list.subList(size / 2, size));

     left.fork();
     right.fork();




}



Thursday, December 6, 12
}else{

     JsonTask left =
                new JsonTask(list.subList(0, size / 2));

     JsonTask right =
                new JsonTask(list.subList(size / 2, size));

     left.fork();
     right.fork();

     jsons.addAll(right.join());
     jsons.addAll(left.join());
}



Thursday, December 6, 12
P




Thursday, December 6, 12
P



                               fork()       fork()




                           L                         R



Thursday, December 6, 12
P

                           join()                         join()

                                    fork()       fork()




                           L                                 R



Thursday, December 6, 12
}else{

     JsonTask left =
                new JsonTask(list.subList(0, size / 2));

     JsonTask right =
                new JsonTask(list.subList(size / 2, size));

     left.fork();
     right.fork();

     jsons.addAll(right.join());
     jsons.addAll(left.join());
}



Thursday, December 6, 12
Pool
    de Threads


                           P




Thursday, December 6, 12
Pool
                           P
    de Threads


                               P




Thursday, December 6, 12
Pool
                               P
    de Threads


                                            P



                                   fork()       fork()




                           L                             R



Thursday, December 6, 12
Pool                                         R
                               P            L
    de Threads


                                                P



                                   fork()               fork()




                           L                                     R



Thursday, December 6, 12
}else{

     JsonTask jsonTaskLeft =
                new JsonTask(list.subList(0, size / 2));

     JsonTask jsonTaskRight =
                new JsonTask(list.subList(size / 2, size));

     jsonTaskLeft.fork();
     jsonTaskRight.fork();

     jsons.addAll(jsonTaskRight.join());
     jsons.addAll(jsonTaskLeft.join());
}



Thursday, December 6, 12
Pool                                         R
                               P            L
    de Threads


                                                P



                                   fork()               fork()




                           L                                     R



Thursday, December 6, 12
RECURSO OCIOSO




Thursday, December 6, 12
}else{

     JsonTask jsonTaskLeft =
                new JsonTask(list.subList(0, size / 2));

     JsonTask jsonTaskRight =
                new JsonTask(list.subList(size / 2, size));

     jsonTaskLeft.fork();
     jsonTaskRight.fork();

     jsons.addAll(jsonTaskRight.join());
     jsons.addAll(jsonTaskLeft.join());
}



Thursday, December 6, 12
}else{

     JsonTask jsonTaskLeft =
                new JsonTask(list.subList(0, size / 2));

     JsonTask jsonTaskRight =
                new JsonTask(list.subList(size / 2, size));

     jsonTaskLeft.fork();
     jsonTaskRight.fork();

     jsons.addAll(jsonTaskRight.join());
     jsons.addAll(jsonTaskLeft.join());
}



Thursday, December 6, 12
}else{

     JsonTask jsonTaskLeft =
                new JsonTask(list.subList(0, size / 2));

     JsonTask jsonTaskRight =
                new JsonTask(list.subList(size / 2, size));

     jsonTaskLeft.fork();



     jsons.addAll(jsonTaskRight.join());
     jsons.addAll(jsonTaskLeft.join());
}



Thursday, December 6, 12
}else{

     JsonTask jsonTaskLeft =
                new JsonTask(list.subList(0, size / 2));

     JsonTask jsonTaskRight =
                new JsonTask(list.subList(size / 2, size));

     jsonTaskLeft.fork();



     jsons.addAll(jsonTaskRight.compute());
     jsons.addAll(jsonTaskLeft.join());
}



Thursday, December 6, 12
Pool
                               P
    de Threads


                                   P




                           L           R



Thursday, December 6, 12
Pool
                               P
    de Threads


                                   P




                           L           R



Thursday, December 6, 12
Pool
                               P
    de Threads


                                            P



                                   fork()




                           L                    R



Thursday, December 6, 12
Pool
                               P
    de Threads


                                            P



                                   fork()




                           L                    R



Thursday, December 6, 12
Pool
                               P            L
    de Threads


                                                P



                                   fork()




                           L                        R



Thursday, December 6, 12
Pool
                               P            L
    de Threads


                                                P



                                   fork()




                           L                        R



Thursday, December 6, 12
Pool
                               P            L
    de Threads


                                                P



                                   fork()           compute()




                           L                                    R



Thursday, December 6, 12
Pool
                               R            L
    de Threads


                                                P



                                   fork()           compute()




                           L                                    R



Thursday, December 6, 12
Pool
                               R            L
    de Threads


                                                P



                                   fork()           compute()




                           L                                    R



Thursday, December 6, 12
Pool
                               R            L
    de Threads


                                                P

                                                            return

                                   fork()           compute()




                           L                                    R



Thursday, December 6, 12
Pool                    P            L
    de Threads


                                                P

                                                            return

                                   fork()           compute()




                           L                                    R



Thursday, December 6, 12
}else{

     JsonTask jsonTaskLeft =
                new JsonTask(list.subList(0, size / 2));

     JsonTask jsonTaskRight =
                new JsonTask(list.subList(size / 2, size));

     jsonTaskLeft.fork();



     jsons.addAll(jsonTaskRight.compute());
     jsons.addAll(jsonTaskLeft.join());
}



Thursday, December 6, 12
Pool
                               P            L
    de Threads


                                                P

                                                            return

                                   fork()           compute()




                           L                                    R



Thursday, December 6, 12
Pool
                                P            L
    de Threads


                                                 P

                           join()                            return

                                    fork()           compute()




                           L                                     R



Thursday, December 6, 12
Pool
                                P
    de Threads


                                             P

                           join()                        return

                                    fork()       compute()




                           L                                 R



Thursday, December 6, 12
EXECUTANDO
 public class JsonForkJoinConverter {
 	
 protected List<String> convertToJson(List<Sale> sales){

     ForkJoinPool forkJoinPool = new ForkJoinPool();
 	 	 return forkJoinPool.invoke(new JsonTask(sales));
 	 }
 }




Thursday, December 6, 12
TEMPO
                                           Tempo
                             Método
                                          Médio (ms)

                              Single         5562

                           Multi Thread      3739

                            Fork/Join        3461




Thursday, December 6, 12
COMPARATIVO
                                  Single     Multi Thread   Fork/join

                           6000



                           4000



                           2000


                                      5562       3739       3461
                              0
                                                 Tempo


Thursday, December 6, 12
@Override
	 protected List<String> compute() {
	 	
	 	 List<String> jsons = new ArrayList<>();
	 	
        int size = list.size();
	 	 if ( size < THRESHOLD){
	 	 	 jsons.addAll(new JsonMapper().toJson(list));
	 	 } else{
        	 JsonTask jsonTaskFirst =
                       new JsonTask(list.subList(0, size / 2));
        	 jsonTaskFirst.fork();
        	
        	 JsonTask jsonTaskSecond =
                       new JsonTask(list.subList(size / 2, size));
        	
        	 jsons.addAll(jsonTaskSecond.compute());
        	 jsons.addAll(jsonTaskFirst.join());
        }

	 	 return jsons;
	 }

Thursday, December 6, 12
PROBLEMS?




Thursday, December 6, 12
PROBLEMS?




Thursday, December 6, 12
A ORDEM DAS CHAMADAS



     • Ordem                das chamadas é importante.



     • Perde               todo o paralelismo



Thursday, December 6, 12
left.fork();
   long rightAns = right.compute();
   long leftAns = left.join();
   return leftAns + rightAns;


                               P



                                   P




                           L           R




Thursday, December 6, 12
left.fork();
   long rightAns = right.compute();
   long leftAns = left.join();
   return leftAns + rightAns;


                               P            L



                                                P



                                   fork()




                           L                        R




Thursday, December 6, 12
left.fork();
   long rightAns = right.compute();
   long leftAns = left.join();
   return leftAns + rightAns;


                               R            L



                                                P



                                   fork()           compute()




                           L                                    R




Thursday, December 6, 12
left.fork();
   long rightAns = right.compute();
   long leftAns = left.join();
   return leftAns + rightAns;


                               P            L



                                                P

                                                            return

                                   fork()           compute()




                           L                                    R




Thursday, December 6, 12
left.fork();
   long rightAns = right.compute();
   long leftAns = left.join();
   return leftAns + rightAns;


                                P



                                             P

                           join()                        return

                                    fork()       compute()




                           L                                 R




Thursday, December 6, 12
left.fork();
   long rightAns = right.compute();
   long leftAns = left.join();
   return leftAns + rightAns;




Thursday, December 6, 12
left.fork();
   long leftAns = left.join();
   long rightAns = right.compute();
   return leftAns + rightAns;




Thursday, December 6, 12
left.fork();
   long leftAns = left.join();
   long rightAns = right.compute();
   return leftAns + rightAns;


                               P



                                   P




                           L           R




Thursday, December 6, 12
left.fork();
   long leftAns = left.join();
   long rightAns = right.compute();
   return leftAns + rightAns;


                               P            L



                                                P



                                   fork()




                           L                        R




Thursday, December 6, 12
left.fork();
   long leftAns = left.join();                      Bloqueia a thread!
   long rightAns = right.compute();
   return leftAns + rightAns;


                               P            L



                                                P



                                   fork()




                           L                        R




Thursday, December 6, 12
left.fork();
   long leftAns = left.join();
   long rightAns = right.compute();
   return leftAns + rightAns;


                                P            L



                                                 P

                           join()

                                    fork()




                           L                         R




Thursday, December 6, 12
left.fork();
   long leftAns = left.join();
   long rightAns = right.compute();
   return leftAns + rightAns;


                                R



                                             P

                           join()

                                    fork()       compute()




                           L                                 R




Thursday, December 6, 12
left.fork();
   long leftAns = left.join();
   long rightAns = right.compute();
   return leftAns + rightAns;


                                R



                                             P

                           join()                        return

                                    fork()       compute()




                           L                                 R




Thursday, December 6, 12
left.fork();
   long leftAns = left.join();
   long rightAns = right.compute();
   return leftAns + rightAns;


                                P



                                             P

                           join()                        return

                                    fork()       compute()




                           L                                 R




Thursday, December 6, 12
long rightAns = right.compute();
   left.fork();
   long leftAns = left.join();
   return leftAns + rightAns;




Thursday, December 6, 12
long rightAns = right.compute();
   left.fork();
   long leftAns = left.join();
   return leftAns + rightAns;


                               P



                                   P




                           L           R




Thursday, December 6, 12
long rightAns = right.compute();
   left.fork();
   long leftAns = left.join();
   return leftAns + rightAns;


                               P



                                   P



                                       compute()




                           L                       R




Thursday, December 6, 12
long rightAns = right.compute();
   left.fork();
   long leftAns = left.join();
   return leftAns + rightAns;


                               R



                                   P



                                       compute()




                           L                       R




Thursday, December 6, 12
long rightAns = right.compute();
   left.fork();
   long leftAns = left.join();
   return leftAns + rightAns;


                               R



                                   P

                                               return

                                       compute()




                           L                       R




Thursday, December 6, 12
long rightAns = right.compute();
   left.fork();
   long leftAns = left.join();
   return leftAns + rightAns;


                               P



                                   P

                                               return

                                       compute()




                           L                       R




Thursday, December 6, 12
long rightAns = right.compute();
   left.fork();
   long leftAns = left.join();
   return leftAns + rightAns;


                               P            L



                                                P

                                                            return

                                   fork()           compute()




                           L                                    R




Thursday, December 6, 12
long rightAns = right.compute();
   left.fork();
   long leftAns = left.join();
   return leftAns + rightAns;


                               P            L



                                                P

                                                            return

                                   fork()           compute()




                           L                                    R




Thursday, December 6, 12
long rightAns = right.compute();
   left.fork();
   long leftAns = left.join();
   return leftAns + rightAns;


                                P



                                             P

                           join()                        return

                                    fork()       compute()




                           L                                 R




Thursday, December 6, 12
long rightAns = right.compute();
   left.fork();                                             Executa
   long leftAns = left.join();                          Sequencialmente
   return leftAns + rightAns;


                                P



                                             P

                           join()                        return

                                    fork()       compute()




                           L                                 R




Thursday, December 6, 12
left.fork();
   long rightAns = right.compute();
   long leftAns = left.join();
   return leftAns + rightAns;




Thursday, December 6, 12
• Código               aqui:

         • github.com/mariofts/javaOneBR-2012

    • Links           / Refs:
         •   http://homes.cs.washington.edu/~djg/teachingMaterials/
             grossmanSPAC_forkJoinFramework.html

         •   http://www.oracle.com/technetwork/articles/java/fork-join-422606.html

         •   http://docs.oracle.com/javase/tutorial/essential/concurrency/forkjoin.html


Thursday, December 6, 12
OBRIGADO!

      github.com/mariofts
      @mario_fts
      mario.amaral@caelum.com.br
Thursday, December 6, 12

More Related Content

Similar to Facilitando a Programação concorrente com o Fork/Join

Thomas risberg mongosv-2012-spring-data-cloud-foundry
Thomas risberg mongosv-2012-spring-data-cloud-foundryThomas risberg mongosv-2012-spring-data-cloud-foundry
Thomas risberg mongosv-2012-spring-data-cloud-foundry
trisberg
 
Introduction to the Disruptor
Introduction to the DisruptorIntroduction to the Disruptor
Introduction to the Disruptor
Trisha Gee
 
Enterprise javascriptsession2
Enterprise javascriptsession2Enterprise javascriptsession2
Enterprise javascriptsession2Troy Miles
 
Introduction To MongoDB
Introduction To MongoDBIntroduction To MongoDB
Introduction To MongoDB
Ynon Perek
 
JavaScript QA Tools
JavaScript QA ToolsJavaScript QA Tools
JavaScript QA Tools
Sebastian Springer
 
Software Libraries And Numbers
Software Libraries And NumbersSoftware Libraries And Numbers
Software Libraries And Numbers
Robert Reiz
 
Kotlin techtalk
Kotlin techtalkKotlin techtalk
Kotlin techtalk
Sergey Lukjanov
 

Similar to Facilitando a Programação concorrente com o Fork/Join (9)

Thomas risberg mongosv-2012-spring-data-cloud-foundry
Thomas risberg mongosv-2012-spring-data-cloud-foundryThomas risberg mongosv-2012-spring-data-cloud-foundry
Thomas risberg mongosv-2012-spring-data-cloud-foundry
 
Introduction to the Disruptor
Introduction to the DisruptorIntroduction to the Disruptor
Introduction to the Disruptor
 
Enterprise javascriptsession2
Enterprise javascriptsession2Enterprise javascriptsession2
Enterprise javascriptsession2
 
Curious case of Dust
Curious case of DustCurious case of Dust
Curious case of Dust
 
Introduction To MongoDB
Introduction To MongoDBIntroduction To MongoDB
Introduction To MongoDB
 
JavaScript QA Tools
JavaScript QA ToolsJavaScript QA Tools
JavaScript QA Tools
 
Software Libraries And Numbers
Software Libraries And NumbersSoftware Libraries And Numbers
Software Libraries And Numbers
 
Kotlin techtalk
Kotlin techtalkKotlin techtalk
Kotlin techtalk
 
[Phind] Miracle
[Phind] Miracle[Phind] Miracle
[Phind] Miracle
 

Recently uploaded

GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
Neo4j
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
Safe Software
 
Large Language Model (LLM) and it’s Geospatial Applications
Large Language Model (LLM) and it’s Geospatial ApplicationsLarge Language Model (LLM) and it’s Geospatial Applications
Large Language Model (LLM) and it’s Geospatial Applications
Rohit Gautam
 
How to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptxHow to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptx
danishmna97
 
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AI
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AIEnchancing adoption of Open Source Libraries. A case study on Albumentations.AI
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AI
Vladimir Iglovikov, Ph.D.
 
Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1
DianaGray10
 
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
James Anderson
 
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
SOFTTECHHUB
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
mikeeftimakis1
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Albert Hoitingh
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
Guy Korland
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Paige Cruz
 
Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
Kari Kakkonen
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
Aftab Hussain
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
Neo4j
 
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
Neo4j
 
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
SOFTTECHHUB
 

Recently uploaded (20)

GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
 
Large Language Model (LLM) and it’s Geospatial Applications
Large Language Model (LLM) and it’s Geospatial ApplicationsLarge Language Model (LLM) and it’s Geospatial Applications
Large Language Model (LLM) and it’s Geospatial Applications
 
How to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptxHow to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptx
 
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AI
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AIEnchancing adoption of Open Source Libraries. A case study on Albumentations.AI
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AI
 
Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1
 
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
 
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
 
Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
 
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
 
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
 

Facilitando a Programação concorrente com o Fork/Join

  • 1. FACILITANDO A PROGRAMAÇÃO CONCORRENTE COM O FORK/JOIN Mário Amaral @mario_fts Thursday, December 6, 12
  • 3. QUE MÁRIO? • Desenvolvedor Java desde 2004 Thursday, December 6, 12
  • 4. QUE MÁRIO? • Desenvolvedor Java desde 2004 • Instrutor na Caelum Thursday, December 6, 12
  • 5. QUE MÁRIO? • Desenvolvedor Java desde 2004 • Instrutor na Caelum • Caelum-Stella Thursday, December 6, 12
  • 6. QUE MÁRIO? • Desenvolvedor Java desde 2004 • Instrutor na Caelum • Caelum-Stella • Personagem de games desde 1981 Thursday, December 6, 12
  • 7. VAMOS FALAR DE PARALELISMO Thursday, December 6, 12
  • 8. POR QUE PARALELIZAR • Ganhar tempo Thursday, December 6, 12
  • 9. POR QUE PARALELIZAR • Aproveitar recursos ociosos Thursday, December 6, 12
  • 11. O QUE PARALELIZAR? • Tarefas Independentes com processamento pesado Thursday, December 6, 12
  • 12. O QUE PARALELIZAR? • Tarefas Independentes com processamento pesado • Processar mensagens de uma fila Thursday, December 6, 12
  • 13. O QUE PARALELIZAR? • Tarefas Independentes com processamento pesado • Processar mensagens de uma fila • Conversão de dados Thursday, December 6, 12
  • 14. O QUE PARALELIZAR? • Tarefas Independentes com processamento pesado • Processar mensagens de uma fila • Conversão de dados • Aplicar filtros em imagens Thursday, December 6, 12
  • 16. O PROBLEMA • Conversão de dados Thursday, December 6, 12
  • 17. O PROBLEMA • Conversão de dados • Dados de vendas Thursday, December 6, 12
  • 18. O PROBLEMA • Conversão de dados • Dados de vendas • CSV => JSON Thursday, December 6, 12
  • 20. OS DADOS • 1;1;04122012;fichario preto;9;33.55 Thursday, December 6, 12
  • 21. OS DADOS • 1;1;04122012;fichario preto;9;33.55 Thursday, December 6, 12
  • 22. OS DADOS • 1;1;04122012;fichario preto;9;33.55 { "number": 1, "terminal": 1, "description": "fichario preto", "price": 33.55, "date": "04122012" } Thursday, December 6, 12
  • 23. PASSO A PASSO • Ler os dados do CSV e converter para objetos. • Para cada objeto, converter em Json. • Adicionar o Json em uma lista de String. • Gravar o conteúdo da lista em um arquivo. Thursday, December 6, 12
  • 24. SINGLE THREAD • Processar tudo sequencialmente em um loop • Implementação mais simples Thursday, December 6, 12
  • 25. CÓDIGO.... public List<String> toJson(List<?> list) { List<String> lines = new ArrayList<>(); for (Object value : list) { lines.add(new JsonObject(value) .toString()); } return lines; } Thursday, December 6, 12
  • 26. TESTANDO •1 milhão de registros • Executar 10 vezes seguidas cada método. • Desconsiderar o menor e o maior tempo. • Obter o tempo médio. Thursday, December 6, 12
  • 27. TEMPO Tempo Método Médio (ms) Single 5562 Thursday, December 6, 12
  • 29. MULTI THREAD • Cada conversão é independente da outra. Thursday, December 6, 12
  • 30. MULTI THREAD • Cada conversão é independente da outra. • Múltiplos processadores Thursday, December 6, 12
  • 31. MULTI THREAD • Cada conversão é independente da outra. • Múltiplos processadores • Dividir e distribuir! Thursday, December 6, 12
  • 32. threads.add(createANewThread(sales, jsons, beginIndex,finalIndex)); Thursday, December 6, 12
  • 33. threads.add(createANewThread(sales, jsons, beginIndex,finalIndex)); beginIndex = finalIndex; finalIndex = finalIndex + amount >= size ? size : finalIndex + amount; Thursday, December 6, 12
  • 34. while (true) { threads.add(createANewThread(sales, jsons, beginIndex,finalIndex)); beginIndex = finalIndex; finalIndex = finalIndex + amount >= size ? size : finalIndex + amount; } Thursday, December 6, 12
  • 35. while (true) { threads.add(createANewThread(sales, jsons, beginIndex,finalIndex)); beginIndex = finalIndex; finalIndex = finalIndex + amount >= size ? size : finalIndex + amount; if (beginIndex == size) { break; } } Thursday, December 6, 12
  • 36. protected List<String> convertToJson(List<Sale> sales){ ... while (true) { threads.add(createANewThread(sales, jsons, beginIndex,finalIndex)); beginIndex = finalIndex; finalIndex = finalIndex + amount >= size ? size : finalIndex + amount; if (beginIndex == size) { break; } } } Thursday, December 6, 12
  • 37. protected List<String> convertToJson(List<Sale> sales){ int size = sales.size(); int amount = size / NUMBER_OF_THREADS; //4 int beginIndex = 0; int finalIndex = amount; List<Thread> threads = new ArrayList<>(); List<String> jsons = Collections.synchronizedList( new ArrayList<String>()); while (true) { //Cria uma nova thread para cada parte } Thursday, December 6, 12
  • 38. protected List<String> convertToJson(List<Sale> sales){ ... for (Thread thread : threads) { thread.start(); } return jsons; } Thursday, December 6, 12
  • 39. protected List<String> convertToJson(List<Sale> sales){ ... for (Thread thread : threads) { thread.start(); } for (Thread thread : threads) { thread.join(); } return jsons; } Thursday, December 6, 12
  • 40. @Override protected List<String> convertToJson(List<Sale> vendas) throws Exception { System.out.println("Convert to json...."); int size = vendas.size(); int amount = size / NUMBER_OF_THREADS; //4 int beginIndex = 0; int finalIndex = amount; List<Thread> threads = new ArrayList<>(); List<String> jsons = Collections.synchronizedList(new ArrayList<String>()); while (true) { threads.add(createANewThread(vendas, jsons, beginIndex, finalIndex)); beginIndex = finalIndex; finalIndex = finalIndex + amount >= size ? size : finalIndex + amount; if (beginIndex == size) { break; } } for (Thread thread : threads) { thread.start(); } for (Thread thread : threads) { thread.join(); } System.out.println("Finished!n "); return jsons; } Thursday, December 6, 12
  • 41. TEMPO Tempo Método Médio (ms) Single 5562 Multi Thread 3739 Thursday, December 6, 12
  • 42. COMPARATIVO Single Multi Thread 6000 4000 2000 5562 3739 0 Tempo Thursday, December 6, 12
  • 44. DIFICULDADES • Decidir a quantidade de Threads Thursday, December 6, 12
  • 45. DIFICULDADES • Decidir a quantidade de Threads • Dividir o trabalho Thursday, December 6, 12
  • 46. DIFICULDADES • Decidir a quantidade de Threads • Dividir o trabalho • Juntar tudo no final Thursday, December 6, 12
  • 47. protected List<String> convertToJson(List<Sale> sales){ int size = sales.size(); int amount = size / NUMBER_OF_THREADS; //4 int beginIndex = 0; int finalIndex = amount; List<Thread> threads = new ArrayList<>(); List<String> jsons = Collections.synchronizedList( new ArrayList<String>()); while (true) { //Cria uma nova thread para cada parte } Thursday, December 6, 12
  • 48. FORK / JOIN Thursday, December 6, 12
  • 49. FORK / JOIN • Java 7 Thursday, December 6, 12
  • 50. FORK / JOIN • Java 7 • Dividir tarefas entre múltiplos processadores Thursday, December 6, 12
  • 51. FORK / JOIN • Java 7 • Dividir tarefas entre múltiplos processadores • Tarefas que podem ser quebradas recursivamente Thursday, December 6, 12
  • 52. COMO FUNCIONA class ExemploForkJoin extends RecursiveTask<Long>{ @Override protected Long compute() { if(qtdeDeDados < LIMITE){ // execute a tarefa }else{ //Divida o trabalho entre subtarefas //Execute as subtarefas e espere o resultado } } } Thursday, December 6, 12
  • 57. COMO FUNCIONA fork() Thursday, December 6, 12
  • 58. COMO FUNCIONA fork() fork() Thursday, December 6, 12
  • 59. COMO FUNCIONA fork() fork() Thursday, December 6, 12
  • 60. COMO FUNCIONA fork() fork() Thursday, December 6, 12
  • 61. COMO FUNCIONA fork() fork() Thursday, December 6, 12
  • 62. COMO FUNCIONA fork() fork() Thursday, December 6, 12
  • 63. COMO FUNCIONA fork() fork() Thursday, December 6, 12
  • 64. COMO FUNCIONA fork() fork() Thursday, December 6, 12
  • 65. COMO FUNCIONA fork() fork() join() Thursday, December 6, 12
  • 66. COMO FUNCIONA fork() fork() join() join() Thursday, December 6, 12
  • 67. COMO FUNCIONA fork() fork() join() join() Thursday, December 6, 12
  • 68. COMO FUNCIONA join() fork() fork() join() join() Thursday, December 6, 12
  • 69. COMO FUNCIONA join() join() fork() fork() join() join() Thursday, December 6, 12
  • 70. IMPLEMENTANDO public class JsonTask extends RecursiveTask<List<String>>{ private final int THRESHOLD = 10000; private List<Sale> list; //constructor... @Override protected List<String> compute() { } } Thursday, December 6, 12
  • 71. IMPLEMENTANDO public class JsonTask extends RecursiveTask<List<String>>{ private final int THRESHOLD = 10000; private List<Sale> list; //constructor... @Override protected List<String> compute() { } } Thursday, December 6, 12
  • 72. IMPLEMENTANDO public class JsonTask extends RecursiveTask<List<String>>{ private final int THRESHOLD = 10000; private List<Sale> list; //constructor... @Override protected List<String> compute() { } } Thursday, December 6, 12
  • 73. IMPLEMENTANDO public class JsonTask extends RecursiveTask<List<String>>{ private final int THRESHOLD = 10000; private List<Sale> list; //constructor... @Override protected List<String> compute() { } } Thursday, December 6, 12
  • 74. @Override protected List<String> compute() { List<String> jsons = new ArrayList<>(); int size = list.size(); if ( size < THRESHOLD){ jsons.addAll(new JsonMapper().toJson(list)); }else{ ... } return jsons; } Thursday, December 6, 12
  • 76. }else{ JsonTask left = new JsonTask(list.subList(0, size / 2)); } Thursday, December 6, 12
  • 77. }else{ JsonTask left = new JsonTask(list.subList(0, size / 2)); JsonTask right = new JsonTask(list.subList(size / 2, size)); } Thursday, December 6, 12
  • 78. }else{ JsonTask left = new JsonTask(list.subList(0, size / 2)); JsonTask right = new JsonTask(list.subList(size / 2, size)); left.fork(); } Thursday, December 6, 12
  • 79. }else{ JsonTask left = new JsonTask(list.subList(0, size / 2)); JsonTask right = new JsonTask(list.subList(size / 2, size)); left.fork(); right.fork(); } Thursday, December 6, 12
  • 80. }else{ JsonTask left = new JsonTask(list.subList(0, size / 2)); JsonTask right = new JsonTask(list.subList(size / 2, size)); left.fork(); right.fork(); jsons.addAll(right.join()); jsons.addAll(left.join()); } Thursday, December 6, 12
  • 82. P fork() fork() L R Thursday, December 6, 12
  • 83. P join() join() fork() fork() L R Thursday, December 6, 12
  • 84. }else{ JsonTask left = new JsonTask(list.subList(0, size / 2)); JsonTask right = new JsonTask(list.subList(size / 2, size)); left.fork(); right.fork(); jsons.addAll(right.join()); jsons.addAll(left.join()); } Thursday, December 6, 12
  • 85. Pool de Threads P Thursday, December 6, 12
  • 86. Pool P de Threads P Thursday, December 6, 12
  • 87. Pool P de Threads P fork() fork() L R Thursday, December 6, 12
  • 88. Pool R P L de Threads P fork() fork() L R Thursday, December 6, 12
  • 89. }else{ JsonTask jsonTaskLeft = new JsonTask(list.subList(0, size / 2)); JsonTask jsonTaskRight = new JsonTask(list.subList(size / 2, size)); jsonTaskLeft.fork(); jsonTaskRight.fork(); jsons.addAll(jsonTaskRight.join()); jsons.addAll(jsonTaskLeft.join()); } Thursday, December 6, 12
  • 90. Pool R P L de Threads P fork() fork() L R Thursday, December 6, 12
  • 92. }else{ JsonTask jsonTaskLeft = new JsonTask(list.subList(0, size / 2)); JsonTask jsonTaskRight = new JsonTask(list.subList(size / 2, size)); jsonTaskLeft.fork(); jsonTaskRight.fork(); jsons.addAll(jsonTaskRight.join()); jsons.addAll(jsonTaskLeft.join()); } Thursday, December 6, 12
  • 93. }else{ JsonTask jsonTaskLeft = new JsonTask(list.subList(0, size / 2)); JsonTask jsonTaskRight = new JsonTask(list.subList(size / 2, size)); jsonTaskLeft.fork(); jsonTaskRight.fork(); jsons.addAll(jsonTaskRight.join()); jsons.addAll(jsonTaskLeft.join()); } Thursday, December 6, 12
  • 94. }else{ JsonTask jsonTaskLeft = new JsonTask(list.subList(0, size / 2)); JsonTask jsonTaskRight = new JsonTask(list.subList(size / 2, size)); jsonTaskLeft.fork(); jsons.addAll(jsonTaskRight.join()); jsons.addAll(jsonTaskLeft.join()); } Thursday, December 6, 12
  • 95. }else{ JsonTask jsonTaskLeft = new JsonTask(list.subList(0, size / 2)); JsonTask jsonTaskRight = new JsonTask(list.subList(size / 2, size)); jsonTaskLeft.fork(); jsons.addAll(jsonTaskRight.compute()); jsons.addAll(jsonTaskLeft.join()); } Thursday, December 6, 12
  • 96. Pool P de Threads P L R Thursday, December 6, 12
  • 97. Pool P de Threads P L R Thursday, December 6, 12
  • 98. Pool P de Threads P fork() L R Thursday, December 6, 12
  • 99. Pool P de Threads P fork() L R Thursday, December 6, 12
  • 100. Pool P L de Threads P fork() L R Thursday, December 6, 12
  • 101. Pool P L de Threads P fork() L R Thursday, December 6, 12
  • 102. Pool P L de Threads P fork() compute() L R Thursday, December 6, 12
  • 103. Pool R L de Threads P fork() compute() L R Thursday, December 6, 12
  • 104. Pool R L de Threads P fork() compute() L R Thursday, December 6, 12
  • 105. Pool R L de Threads P return fork() compute() L R Thursday, December 6, 12
  • 106. Pool P L de Threads P return fork() compute() L R Thursday, December 6, 12
  • 107. }else{ JsonTask jsonTaskLeft = new JsonTask(list.subList(0, size / 2)); JsonTask jsonTaskRight = new JsonTask(list.subList(size / 2, size)); jsonTaskLeft.fork(); jsons.addAll(jsonTaskRight.compute()); jsons.addAll(jsonTaskLeft.join()); } Thursday, December 6, 12
  • 108. Pool P L de Threads P return fork() compute() L R Thursday, December 6, 12
  • 109. Pool P L de Threads P join() return fork() compute() L R Thursday, December 6, 12
  • 110. Pool P de Threads P join() return fork() compute() L R Thursday, December 6, 12
  • 111. EXECUTANDO public class JsonForkJoinConverter { protected List<String> convertToJson(List<Sale> sales){ ForkJoinPool forkJoinPool = new ForkJoinPool(); return forkJoinPool.invoke(new JsonTask(sales)); } } Thursday, December 6, 12
  • 112. TEMPO Tempo Método Médio (ms) Single 5562 Multi Thread 3739 Fork/Join 3461 Thursday, December 6, 12
  • 113. COMPARATIVO Single Multi Thread Fork/join 6000 4000 2000 5562 3739 3461 0 Tempo Thursday, December 6, 12
  • 114. @Override protected List<String> compute() { List<String> jsons = new ArrayList<>(); int size = list.size(); if ( size < THRESHOLD){ jsons.addAll(new JsonMapper().toJson(list)); } else{ JsonTask jsonTaskFirst = new JsonTask(list.subList(0, size / 2)); jsonTaskFirst.fork(); JsonTask jsonTaskSecond = new JsonTask(list.subList(size / 2, size)); jsons.addAll(jsonTaskSecond.compute()); jsons.addAll(jsonTaskFirst.join()); } return jsons; } Thursday, December 6, 12
  • 117. A ORDEM DAS CHAMADAS • Ordem das chamadas é importante. • Perde todo o paralelismo Thursday, December 6, 12
  • 118. left.fork(); long rightAns = right.compute(); long leftAns = left.join(); return leftAns + rightAns; P P L R Thursday, December 6, 12
  • 119. left.fork(); long rightAns = right.compute(); long leftAns = left.join(); return leftAns + rightAns; P L P fork() L R Thursday, December 6, 12
  • 120. left.fork(); long rightAns = right.compute(); long leftAns = left.join(); return leftAns + rightAns; R L P fork() compute() L R Thursday, December 6, 12
  • 121. left.fork(); long rightAns = right.compute(); long leftAns = left.join(); return leftAns + rightAns; P L P return fork() compute() L R Thursday, December 6, 12
  • 122. left.fork(); long rightAns = right.compute(); long leftAns = left.join(); return leftAns + rightAns; P P join() return fork() compute() L R Thursday, December 6, 12
  • 123. left.fork(); long rightAns = right.compute(); long leftAns = left.join(); return leftAns + rightAns; Thursday, December 6, 12
  • 124. left.fork(); long leftAns = left.join(); long rightAns = right.compute(); return leftAns + rightAns; Thursday, December 6, 12
  • 125. left.fork(); long leftAns = left.join(); long rightAns = right.compute(); return leftAns + rightAns; P P L R Thursday, December 6, 12
  • 126. left.fork(); long leftAns = left.join(); long rightAns = right.compute(); return leftAns + rightAns; P L P fork() L R Thursday, December 6, 12
  • 127. left.fork(); long leftAns = left.join(); Bloqueia a thread! long rightAns = right.compute(); return leftAns + rightAns; P L P fork() L R Thursday, December 6, 12
  • 128. left.fork(); long leftAns = left.join(); long rightAns = right.compute(); return leftAns + rightAns; P L P join() fork() L R Thursday, December 6, 12
  • 129. left.fork(); long leftAns = left.join(); long rightAns = right.compute(); return leftAns + rightAns; R P join() fork() compute() L R Thursday, December 6, 12
  • 130. left.fork(); long leftAns = left.join(); long rightAns = right.compute(); return leftAns + rightAns; R P join() return fork() compute() L R Thursday, December 6, 12
  • 131. left.fork(); long leftAns = left.join(); long rightAns = right.compute(); return leftAns + rightAns; P P join() return fork() compute() L R Thursday, December 6, 12
  • 132. long rightAns = right.compute(); left.fork(); long leftAns = left.join(); return leftAns + rightAns; Thursday, December 6, 12
  • 133. long rightAns = right.compute(); left.fork(); long leftAns = left.join(); return leftAns + rightAns; P P L R Thursday, December 6, 12
  • 134. long rightAns = right.compute(); left.fork(); long leftAns = left.join(); return leftAns + rightAns; P P compute() L R Thursday, December 6, 12
  • 135. long rightAns = right.compute(); left.fork(); long leftAns = left.join(); return leftAns + rightAns; R P compute() L R Thursday, December 6, 12
  • 136. long rightAns = right.compute(); left.fork(); long leftAns = left.join(); return leftAns + rightAns; R P return compute() L R Thursday, December 6, 12
  • 137. long rightAns = right.compute(); left.fork(); long leftAns = left.join(); return leftAns + rightAns; P P return compute() L R Thursday, December 6, 12
  • 138. long rightAns = right.compute(); left.fork(); long leftAns = left.join(); return leftAns + rightAns; P L P return fork() compute() L R Thursday, December 6, 12
  • 139. long rightAns = right.compute(); left.fork(); long leftAns = left.join(); return leftAns + rightAns; P L P return fork() compute() L R Thursday, December 6, 12
  • 140. long rightAns = right.compute(); left.fork(); long leftAns = left.join(); return leftAns + rightAns; P P join() return fork() compute() L R Thursday, December 6, 12
  • 141. long rightAns = right.compute(); left.fork(); Executa long leftAns = left.join(); Sequencialmente return leftAns + rightAns; P P join() return fork() compute() L R Thursday, December 6, 12
  • 142. left.fork(); long rightAns = right.compute(); long leftAns = left.join(); return leftAns + rightAns; Thursday, December 6, 12
  • 143. • Código aqui: • github.com/mariofts/javaOneBR-2012 • Links / Refs: • http://homes.cs.washington.edu/~djg/teachingMaterials/ grossmanSPAC_forkJoinFramework.html • http://www.oracle.com/technetwork/articles/java/fork-join-422606.html • http://docs.oracle.com/javase/tutorial/essential/concurrency/forkjoin.html Thursday, December 6, 12
  • 144. OBRIGADO! github.com/mariofts @mario_fts mario.amaral@caelum.com.br Thursday, December 6, 12