#Please please help me with this ExecutorService code

1 messages · Page 1 of 1 (latest)

wispy moss
#

I'm really new to concurrency in java.

This is the ExecutorService code:
ExecutorService pool = Executors.newFixedThreadPool(7);
List<Future<Hotel>> future = new ArrayList<>();
List<Callable<Hotel>> callList = new ArrayList<>();

for (int i = 0; i <= diff; i++) {
String str = "2013-" + (liDates.get(i).get(Calendar.MONTH) + 1) + "-" + liDates.get(i).get(Calendar.DATE);
callList.add(new HotelCheapestFare(str));
}

future = pool.invokeAll(callList);

for (int i = 0; i < future.size(); i++) {
System.out.println("name is: " + future.get(i).get().getName());
}

Now my question is, why can't i write it like:
List<Hotel> result=new ArrayList<>();

for (int i = 0; i <= diff; i++) {
String str = "2013-" + (liDates.get(i).get(Calendar.MONTH) + 1) + "-" + liDates.get(i).get(Calendar.DATE);
result.add(new HotelCheapestFare(str));
}
for (int i = 0; i < result.size(); i++) {
System.out.println("name is: " + result.get(i).getName());
}

I know that ExecutorService.invokeAll() executes all the Callable<T> in the thread pool parallely, but
for (int i = 0; i <= diff; i++) {
String str = "2013-" + (liDates.get(i).get(Calendar.MONTH) + 1) + "-" + liDates.get(i).get(Calendar.DATE);
callList.add(new HotelCheapestFare(str));
}
this part of the code is not being run in the thread pool right? then what even is the use of using thread pool here

paper walrusBOT
#

<@&1004656351647117403> please have a look, thanks.

#

Here is an AI assisted attempt to answer your question 🤖. Maybe it helps! In any case, a human is on the way 👍. To continue talking to the AI, you can use </chatgpt:1108714622413963314>.

#

futureList = new ArrayList<>();

for (int i = 0; i < 10; i++) {
Future<Hotel> future = pool.submit(new HotelCallable(i));
futureList.add(future);
}

for (Future<Hotel> future : futureList) {
try {
Hotel hotel = future.get();
System.out.println("Hotel details: " + hotel);
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}

pool.shutdown();

tawny turret
#

bot answer is a reasonable start.

wispy moss
#

No sir hear me out pls

#

The for loop is not being executed by the threadpool right? Java main thread is executing it.

#

Then why can't i just create objects directly and return them.

tawny turret
#

You can. It will be sequential. 1) build the request string, 2)do whatever HotelCallable does, 3) return the result to a list.