I'm trying to execute some parallel methods inside my controller but i'm having a few problems with the return type.
I have 4 methods and each of those methods return a list.I need to execute those methods in a parallel way and then get each returned list and place all of those lists inside a map and return that map from the controller. Here's the code:
Callable<List> callable1 = new Callable<List>()
{
@Override
public List call() throws Exception
{
List<SearchResultAutovit> lista;
lista = scrapperAutovit.searchAutovit(marcaId, modelId, pretDeLa, pretPanaLa, anFabrDeLa, anFabrPanaLa,
orasParam);
return lista;
}
};
Callable<List> callable2 = new Callable<List>()
{
@Override
public List call() throws Exception
{
List<SearchResultOlx> listaOlx;
String marcaOlx = marcaId.toLowerCase();
String modelOlx = modelId.toLowerCase();
String orasOlx = orasParam.toLowerCase();
listaOlx = scrapperOlx.searchOlx(marcaOlx, modelOlx, pretDeLa, pretPanaLa, anFabrDeLa, anFabrPanaLa, orasOlx);
return listaOlx;
}
};
Callable<List> callable3 = new Callable<List>()
{
@Override
public List call() throws Exception
{
List<SearchResultPubli24> listaPubli24;
String orasPubli24 = orasParam.toLowerCase();
listaPubli24 = scrapperPubli24.searchPubli24(marcaId, modelId, orasPubli24, anFabrDeLa, anFabrPanaLa, pretDeLa, pretPanaLa);
return listaPubli24;
}
};
Callable<List> callable4 = new Callable<List>()
{
@Override
public List call() throws Exception
{
List<SearchResultAutoUncle> listaAutoUncle;
listaAutoUncle = scrapperAutoUncle.searchAutoUncle(marcaId, modelId, pretDeLa, pretPanaLa, anFabrDeLa, anFabrPanaLa, orasParam);
return listaAutoUncle;
}
};
//add to a list
List<Callable<List>> taskList = new ArrayList<Callable<List>>();
taskList.add(callable1);
taskList.add(callable2);
taskList.add(callable3);
taskList.add(callable4);
ExecutorService executor = Executors.newFixedThreadPool(3);
executor.invokeAll(taskList);
Map<String,List<?>> listOfWebsites = new HashMap<>();
listOfWebsites.put("listaAutovit", (List<?>) taskList.get(0));
listOfWebsites.put("listaOlx", (List<?>) taskList.get(1));
listOfWebsites.put("listaPubli24", (List<?>) taskList.get(2));
listOfWebsites.put("listaAutoUncle", (List<?>) taskList.get(3));
return listOfWebsites;
I'm pretty sure that i'm not doing something right because it throws java.lang.ClassCastException: com.test.controller.HomeController$1 incompatible with java.util.List
I guess the problem is the map called listOfWebsites which should have the returned type of the callables, some lists:(
HomeController$1is yourCallable... More generally though, you should plan to do the whole process asynchronously and return aFuturefrom your controller method.