16

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 ?

Community
  • 1
  • 1
user3430459
  • 271
  • 3
  • 7

3 Answers3

18

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
telkins
  • 10,440
  • 8
  • 52
  • 79
  • just saw your website. it would be nice if you put 3 android interview questions on there – user3430459 Apr 16 '14 at 16:36
  • @user3430459 Definitely, once I get some time to do it. :) – telkins Apr 16 '14 at 17:20
  • 1
    @trevor-e I think you meant to write "ExecutorThreadPool" instead of "Executor". ExecutorThreadPool manages and distributes tasks to pooled threads if available like you pretty much explained. An Executor is an object used to execute Runnable tasks. – user3144836 Jun 11 '16 at 19:13
2

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.

Alex Cohn
  • 56,089
  • 9
  • 113
  • 307
1

Let me add that android looper can be used by native code. The Android Looper system is made up of the Looper class, Handler class, MesseageQueue class. One looper is bounded to one thread. From Andorid 4.0, MessageQueue is implemented by both java code and c code, which are connected. You can send a message to the same MessageQueue via native code or java code.

So the difference are:

  1. Looper is simple with one thread, however ExecutorThreadPool is complicated and flexible with one or more threads.

  2. Looper can be conveniently used by native code.

Besides, Looper and Handler is commonly used in Android code. Some android developers are more farmilar with Handler than ExecutorThreadPool.

Tyrael
  • 31
  • 3