I have the following code snippet and I'm wondering if submitting instances of Runnable
in a loop is good practice when running tasks on a thread pool.
I need to have access to the list outside the loop which is my reasoning. This is pseudo code, so my real code uses ConcurrentHashMap's, eliminating thread issues. If this is bad practice, does anybody have any better recommendations? I tried splitting this off into another class, but ran into issues with my outside list.
I had troubles knowing when to clear the list out of memory, I had no way of knowing when the threads all completed.
public void startJob() {
int threads = Runtime.getRuntime().availableProcessors();
ExecutorService exec = Executors.newFixedThreadPool(threads);
final List<ImportTask> importTasks = session.createCriteria(ImportTask.class).list();
final List<Object> objs = new ArrayList<>();
int count = 0;
for (ImportTask importTask : importTasks) {
exec.submit(new Runnable() {
@Override
public void run() {
count++;
if(objs.contains(importTask) {
obj = objs.get(importTask.indexOf(importTask));
} else {
Object obj = new Object();
objs.add(obj);
session.save(obj);
}
if(count % 50 = 1000) {
session.flush();
session.commit();
}
}
}
}
}