Created 2 task which insert values inside list .
Then execute those task using executor service .
And at last try to find out the values inside those list .
Why values are not inserted into list once executor service is shutdown ?
Not able to find out the reason behind this behavior , can any one explain this .
package com.executors;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicInteger;
public class ExecutorTesting {
public static AtomicInteger counter = new AtomicInteger(0);
static List<employee> list = new ArrayList<employee>();
public static void main(String[] args) throws InterruptedException, ExecutionException {
list = Collections.synchronizedList(list);
Callable<List<employee>> c1 = new Callable<List<employee>>() {
@Override
public List<employee> call() throws Exception {
for (int i = 0; i < 10; i++) {
list.add(new employee("varun", ExecutorTesting.counter.incrementAndGet()));
}
return list;
}
};
Callable<List<employee>> c2 = new Callable<List<employee>>() {
@Override
public List<employee> call() throws Exception {
for (int i = 0; i < 10; i++) {
list.add(new employee("varun", ExecutorTesting.counter.incrementAndGet()));
}
return list;
}
};
ExecutorService es = Executors.newFixedThreadPool(2);
try {
Future<List<employee>> ef1 = es.submit(c1);
Future<List<employee>> ef2 = es.submit(c2);
if (ef1.isDone()) {
System.out.println("first value : " + ef1.get());
}
if (ef2.isDone()) {
System.out.println("first value : " + ef2.get());
}
System.out.println(list);
} finally {
es.shutdown();
}
}
}
class employee {
String name;
int id;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public employee(String name, int id) {
super();
this.name = name;
this.id = id;
}
public String toString() {
return this.name + " : " + this.id;
}
}
You're calling future.isDone()
immediately after submitting it to the ExecuterService
. In most cases the execution will not have been started, let alone be finished. So both isDone
calls return false
and you just finish the whole thing.
I'm not sure about the concrete scenario you're facing, but to solve the problem in this particular test code, you just need to call get
on each Future
:
System.out.println("first value : " + ef1.get(10, TimeUnit.SECONDS));
System.out.println("first value : " + ef2.get(10, TimeUnit.SECONDS));
I left your copy&paste-error of your output-text ;-)