With below code snippet,
String[][] users = {user1, user2, user3, user4, user5};
Queue<Form> formList = new ArrayBlockingQueue<>(5);
Executor executor = Executors.newCachedThreadPool();
executor.execute(() -> {
System.out.println(Thread.currentThread().getName());
for(String[] user: users) {
Form f = new Form(user[0], user[1], user[2], user[3], user[4]);
formList.add(f);
}
});
System.out.println(formList);
I want to stored all form created inside lambda in formList (queue). But it gives me empty queue at the end. Any suggestion
You're asking the executor to execute a task on another thread. This may take time to spin up the necessary thread(s) and perform the work, and in the mean time, your main thread has already printed the current content of formList
(i.e. nothing).
To be able to print the result of your tasks, you need to wait until the tasks are completed, for example by shutting down the ExecutorService
and awaiting termination, or by using ExecutorService.submit
instead of Executor.execute
, and collect the returned futures and use get
on all those futures to await their completion. There also a lot of other options, like using a CompletionService
, or CompletableFuture
, etc.