简体   繁体   中英

multiple ExecutorService.execute() calls. Threadpool. Redundancy?

I am using the java.util.concurrent.ExecutorService and I am wondering if accidental redundant usage would use more resources or is just slower. I mean if I would run

executor.execute(() -> executor.execute(() -> something());

Knowing that I'm using a ThreadPool, which the Executor will choose from, I'm not sure what he does after executing the above code.

Does it have bad side effects or does it need more resources to execute? Or how does the Executor choose between pool and calling thread?( The command may execute in a new thread, in a pooled thread, or in the calling thread,[..] )

Regards Lukas

No, the executor will not check if you are already in a thread, because it's always the case. You can see it with the debugger.

It will be slower and use more resources. Creating a thread is a long process (from the CPU point of view), and having too much thread makes the CPU changes the context all the time and reduces performance.

You cited the documentation, I think you misunderstood this sentence. They are about where your task (Runnable, Callable...) will be executed.

  • New thread: The executor will create a new thread
  • Pooled thread: The executor will queue the task and one of the thread in it's thread pool will take it when possible (Pooled thread never stop, you avoid the creation process)
  • Calling thread: execute it on the thread where you called execute()

Edit: Regarding to your code, what will happen is pretty simple:

  1. The executor queue the task, which is a lambda here.
  2. A thread from the thread pool will take this task as soon as possible (the queue is shared across Thread, so there is semaphore/synchronized behind the scene)
  3. The lambda is executed inside the thread, and the final task will be queued.
  4. A thread from the thread pool will take this task as soon as possible
  5. And finally your function something() is called !

There is no "bad side effect", but unnecessary overhead. Also, the executor don't choose anything. It depends with executor you instanced from any of the static method in the Executors class. It's you who choose if you want a thread pool, mono thread or current

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM