Reputation: 51
I have a problem with my program. In loop i creating a new Employes (automatically by downloading data from the fake name generator website) in multiThread (this is the premise of my exercise) and if thread finish creating Employee object should to add this to synchronized List but something going wrong and list is empty. Im stuck. Someone know what is wrong?
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Stream;
public class Main {
public static void main(String[] args) throws Exception {
final String[][] e = new String[1][1];
EmployeesGenerator a=new EmployeesGenerator();
List<Employees> list= Collections.synchronizedList(new ArrayList<>());
ExecutorService executorService= Executors.newFixedThreadPool(10);
for(int x=0; x<10;x++){
executorService.submit(()->{
try {
e[0] =a.getEmployees();
} catch (Exception ex) {
ex.printStackTrace();
}
list.add(new Employees(e[0][0], e[0][1], e[0][2], e[0][3], e[0][4]));
}
);
}
executorService.shutdown();
System.out.println(list.size());
}
}
Upvotes: 0
Views: 81
Reputation: 466
you should wait for the termination of the threads after the shutdown of the executorService:
try {
executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
} catch (InterruptedException e) {
}
System.out.println(list.size());
Upvotes: 1