Reputation: 299
So I am attempting to start a new thread from within a thread.
i.e.
function(update):
under certain conditions:
add a new thread running same service as current
Ideally I would like the new thread to run and my current thread to continue executing.
Instead, a new thread is created but only when it is completed does my host thread continue again.
Ideally I need it to execute concurrently, where adding a new thread has the same effect as adding a thread from my originating class.
How can i do this with executor service?
I'm currently initialising as follows:
ExecutorService executorService = Executors.newFixedThreadPool(100);
Add thread function:
final SimulatedAnnealingCallable simulatedAnnealingCallable =
new SimulatedAnnealingCallable(this, schedule);
final Future<Schedule> future = executorService.submit(simulatedAnnealingCallable);
try {
future.get();
} catch (ExecutionException ex) {
ex.getCause().printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
Shutdown occurs later
Upvotes: 0
Views: 172
Reputation: 401
The reason is that you are blocking your main thread in the future.get().
what actually happens is that your main thread starts a new future task with the executor and than you block the main thread by telling it to wait for the results of the executing task.
one way to handle this is not waiting for the future to complete and instead add functionality to let you know the task has completed using callable.
for example
public interface CompletedTask {
void completed(boolean succes);
}
// change SimulatedAnnealingCallable to receive CompletedTask in constructor
// and call the instanc's completed method
public LogicClass implements CompletedTask {
private void someFunc() {
final SimulatedAnnealingCallable simulatedAnnealingCallable =
new SimulatedAnnealingCallable(this, schedule);
executorService.submit(simulatedAnnealingCallable);
}
public void completed(boolean succes) {
System.out.println("task is completed with " + success);
}
}
HTH, Gal
Upvotes: 1