Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Single thread pool - ExecutorService or Handler + HandlerThread

Traditionally, when I need a single thread pool, I will use

ExecutorService executorService = Executors.newSingleThreadExecutor();
executorService.submit(...

However, when look at Weather List Widget, I realize that we can use Handler + HandlerThread to achieve the similar objective

HandlerThread sWorkerThread = new HandlerThread("WeatherWidgetProvider-worker");
sWorkerThread.start();
Handler sWorkerQueue = new Handler(sWorkerThread.getLooper());
sWorkerQueue.post(...

I was wondering, what is the consideration I should take, in order have a right choice among them?

like image 455
Cheok Yan Cheng Avatar asked Oct 16 '25 20:10

Cheok Yan Cheng


1 Answers

HandlerThread is simpler than than ExecutorService. So it will use less resources and work faster. So if you have a lot of small messages process them via Handler.

But Executors it's not just a class. Executors is a standart. It's a framework with a lot of features and every java programmer can understand your code written with executors. A lot of libraries can work with executors. It's flexible, you can easily change executor type or executor queue. So if you have a complex processing task and you do not know how exactly implement it use executors.

like image 86
Leonidos Avatar answered Oct 18 '25 11:10

Leonidos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!