Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

difference between android looper and executor thread pool

Tags:

java

android

I was reading about loopers , and also on Executor Thread Pools and they appear to be doing the exact same thing... or am I missing something ?

like image 553
user3430459 Avatar asked Apr 16 '14 16:04

user3430459


2 Answers

A Looper manages tasks that a Thread will run. It puts them in a queue and then the Thread takes the next task in line. A Looper is tied to a specific Thread.

An Executor encapsulates managing and distributing tasks to different Threads. If you have a fixed threadpool size of 1 then I suppose it would be similar in design to a Looper because it will just queue up the work for that one Thread. If you have a threadpool with size > 1 then it will manage giving the task to the next Thread available to do the work, or in other words it will distribute tasks among all threads.

edit: Recommended reading: http://developer.android.com/reference/java/util/concurrent/package-summary.html

Executors are more flexible. For Android, the only time I really use Looper is when trying to make a Handler to communicate with the main thread from a background thread (which could even be in an ExecutorService). For example:

Handler mainThreadHandler = new Handler(Looper.getMainLooper());
mainThreadHandler.post(new Runnable...); //runs on main thread
like image 194
telkins Avatar answered Sep 20 '22 11:09

telkins


It might be important to note that AndroidX defines HandlerExecutor. Same class is available from GMS. This is an executor that uses a Handler that can be built on any looper. For example, this way we can get an Executor for Main thread on API level < 28.

like image 41
Alex Cohn Avatar answered Sep 23 '22 11:09

Alex Cohn