I am trying to create a threadPool from a collections of objects. There are 1000 objects in the collections. Each objects calls a function to a get a string list and store them in a Output String list.
But the problem here is I have to spawn around 1000 threads to fetch the list simultaneously or I have to sequentially iterate through the list and fetch the list of String list.
So what I am trying to do here, instead of having only 1 object per thread. I am having a collection of X objects per thread(10 objects per thread). Then loop through the objects moving each one.
Is there any way instead of looping through the objects to directly create a threadpool or a executor service?
Or Is there any other way of working this problem around?
---- main thread -----
(thread1) | (thread2)| (thread3)|
group1 group2 group3
(Subthreads) | | | | | |
obj1 obj2 obj3 obj obj5 obj6
public class ExampleApplication {
static List<String> outputList = new ArrayList<String>();
static ExecutorService executor = Executors.newScheduledThreadPool(10);
public static void main(String[] args) throws InterruptedException {
List<Customer> list = new ArrayList<Customer>();
//Example list of Object Collection
for (int i = 0; i < 100; i++) {
list.add(new Customer());
}
executor.execute(new Query(list.subList(0, 25)));
executor.execute(new Query(list.subList(26, 50)));
executor.execute(new Query(list.subList(51, 75)));
executor.execute(new Query(list.subList(76, 100)));
executor.shutdown();
}
static class Query implements Runnable {
List<Customer> list;
public Query(List<Customer> list) {
// TODO Auto-generated constructor stub
this.list = list;
}
@Override
public void run() {
// TODO Auto-generated method stub
for (Customer customer : list) {
//Adds a list of String to this output list
//customer.rec() returns a list of String
outputList.addAll(customer.rec());
}
}
}
}
Above is an example problem. Here I created a threadpool of 10, In the Query class, I am kind of iterating the list of objects to fetch the String list. So Instead of iterating the collection of object, is there any way to make it to collection of X objects per thread(10 objects per thread). Is there any example I can refer to?