I need to execute parallel tasks in a web application. Right now, I have a java class that implements a Callable, where DMI is an object that I use in a JSF bean.
The problem is that all Callable objects are running in the same thread, then only after a complete execution of all of them, the thread changes. I want to run every object on a different thread. What am I doing wrong?
Class Callable
public class ModuloCallable implements Callable<DMI> {
private final String NOME;
private final String URL;
public ModuloCallable(String nome, String url) {
this.NOME = nome;
this.URL = url;
}
@Override
public DMI call() {
try {
/* Some code here to generate a DMI object */
System.out.println("Thread number: " + Thread.currentThread().getId());
return dmi;
}
} catch (NullPointerException e) {
return null;
}
return null;
}
}
JSF Bean
@Named(value = "dmiBean")
@RequestScoped
public class DmiBean {
private DMI geradorG1;
private DMI geradorG2;
private DMI geradorG3;
/**
* Creates a new instance of DmiBean
*/
public DmiBean() {
}
@PostConstruct
public void buscar() {
ExecutorService executor = Executors.newCachedThreadPool();
ModuloCallable G1C = new ModuloCallable("n1", "url1")
ModuloCallable G2C = new ModuloCallable("n2","url2");
ModuloCallable G3C = new ModuloCallable("n3","url3");
geradorG1 = getFutureValue(G1C, executor);
geradorG2 = getFutureValue(G2C, executor);
geradorG3 = getFutureValue(G3C, executor);
executor.shutdown();
}
public DMI getFutureValue(ModuloCallable mc, ExecutorService e) {
Future<DMI> f = e.submit(mc);
DMI dmi;
try {
dmi = f.get();
return dmi;
} catch (InterruptedException | ExecutionException ex) {
System.out.println(ex.getMessage());
return null;
}
}
}
Example of output
Thread number: 150
Thread number: 150
Thread number: 150
If i use a p:poll to call the PostConstruct method continuously, than i would have something like:
Thread number: 150
Thread number: 150
Thread number: 150
Thread number: 151
Thread number: 151
Thread number: 151
I want something like:
Thread number: 148
Thread number: 149
Thread number: 150
Aucun commentaire:
Enregistrer un commentaire