Your base question was answered, I just want to comment on execute
vs. submit
.
Basically neither of them are guaranteed to execute your code immediately. If the pool is overloaded with tasks, it will have to wait until all the previous tasks in the queue are finished before executing your task.
Now, you can see the difference in method signature:
void execute(Runnable command)
public Future<?> submit(Runnable task)
Hence, submit allows you to get a Future
reference that you can later use to wait for the task to finish or cancel it if you want.
Bonus, to fully clear things up, having a look at the source of AbstractExecutorService, we can see that the implementation of submit
is in fact:
103 /**
104 * @throws RejectedExecutionException {@inheritDoc}
105 * @throws NullPointerException {@inheritDoc}
106 */
107 public Future<?> submit(Runnable task) {
108 if (task == null) throw new NullPointerException();
109 RunnableFuture<Void> ftask = newTaskFor(task, null);
110 execute(ftask);
111 return ftask;
112 }
In line 110 you can see that it actually calls execute
, therefore their functionality is identical, modulo the Future
part.