I would like to use Java fork join to solve a recursive problem, but I don't want to create a new task instance explicitly for each recursion step. The reason is that too many tasks is equal to too many objects which fills up my memory after a few minutes of processing.
I have the following solution in Java 6, but is there a better implementation for Java 7?
final static AtomicInteger max = new AtomicInteger(10); // max parallel tasks
final static ThreadPoolExecutor executor = new ThreadPoolExecutor(....);
private void submitNewTask() {
if (max.decrementAndGet()>=0) {
executor.execute(new Task(....));
return;
}
run(); // avoid creating a new object
}
public void run() {
..... process ....
// do the recursion by calling submitNewTask()
max.incrementAndGet();
}
I tried something like calling the invoke()
function on the same task again (after updating the related fields, of course), but it does not seem to work.