Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Thread to be favoured over Executor here?

As far as I understand Executors help handling the execution of runnables. E.g. I would choose using an executor when I have several worker threads that do their job and then terminate. The executor would handle the creation and the termination of the Threads needed to execute the worker runnables.

However now I am facing another situation. A fixed number of classes/objects shall encapsulate their own thread. So the thread is started at the creation of those objects and the Thread shall continue running for the whole life time of these objects. The few objects in turn are created at the start of the programm and exist for the whole run time. I guess Threads are preferable over Executors in this situation, however when I read the internet everybody seems to suggest using Executors over Threads in any possible situation.

Can somebody please tell me if I want to choose Executors or Threads here and why?

Thanks

like image 393
flxh Avatar asked Feb 11 '15 21:02

flxh


People also ask

How many threads does an executor service have?

Executors Framework While it is easy to create one or two threads and run them, it becomes a problem when your application requires creating 20 or 30 threads for running tasks concurrently.

Why is the executor framework better than creating and managing threads via the application?

Why use it? The Executor Framework contains a bunch of components that are used to efficiently manage multiple threads. It was released with the JDK 5 which is used to run the Runnable objects without creating new threads every time and also mostly re-using the already created threads.

How does thread pool executor work internally?

ThreadPool Executor has the CorePoolSize which governs how many active threads spawn up, with every incoming request. Once the CorePoolSize threads are active, new incoming tasks are added to the Queue, and these threads are actively polling from the Queue to execute them.

What is Thread pool executor?

ThreadPoolExecutor is an ExecutorService to execute each submitted task using one of possibly several pooled threads, normally configured using Executors factory methods. It also provides various utility methods to check current threads statistics and control them.


1 Answers

You're somewhat mixing things. Executor is just an interface. Thread is a core class. There's nothing which directly implies that Executor implementations execute tasks in separate threads.

Read the first few lines of the JavaDoc.

Executor

So if you want full control, just use Thread and do things on your own.

like image 100
peter.petrov Avatar answered Oct 04 '22 04:10

peter.petrov