Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Runnable or Executor Service

Which is easier and more suitable to use for running things in another thread, notably so that the program waits for the result but doesn't lock up an ui.

There may be a method that is better than either of these also, but I don't know of them.

Thanks :)

like image 600
Cooltrooper Avatar asked Apr 12 '13 20:04

Cooltrooper


People also ask

What is an Executor service?

The executor service creates and maintains a reusable pool of threads for executing submitted tasks. The service also manages a queue, which is used when there are more tasks than the number of threads in the pool and there is a need to queue up tasks until there is a free thread available to execute the task.

What is executable service?

The ExecutorService helps in maintaining a pool of threads and assigns them tasks. It also provides the facility to queue up tasks until there is a free thread available if the number of tasks is more than the threads available.

Do we need to shutdown Executor service?

Upon termination, an executor has no tasks actively executing, no tasks awaiting execution, and no new tasks can be submitted. An unused ExecutorService should be shut down to allow reclamation of its resources. Method submit extends base method Executor.

What is Executor in multithreading?

Executors provide factory methods that are being used to create ThreadPools of worker threads. Thread pools overcome this issue by keeping the threads alive and reusing the threads. Any excess tasks flowing in that the threads in the pool can handle are held in a Queue.


1 Answers

  • Runnable represents the code to be executed.
  • Executor and its subclasses represent execution strategies.

This means that the former is actually consumed by the later. What you probably meant is: between simple threads and executors, which are more suitable?

The answer to this question is basically: it depends.

Executors are sophisticated tools, which let you choose how many concurrent tasks may be running, and tune different aspects of the execution context. They also provide facilities to monitor the tasks' executions, by returning a token (called a Future or sometimes a promise) which let the code requesting the task execution to query for that task completion.

Threads are less elaborate (or more barebone) a solution to executing code asynchronously. You can still have them return a Future by hand, or simply check if the thread is still running.

So maybe depending on much sophistication you require, you will pick one or the other: Executors for more streamlined requirements (many tasks to execute and monitor), Threads for one shot or simpler situations.

like image 64
didierc Avatar answered Oct 07 '22 10:10

didierc