Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ScheduledExecutorService vs Timer vs Handler

What are the pros and cons of using ScheduledExecutorService / Timer / Handler? As I understand in Android instead of Timer it's need to use Handler, but what about ScheduledExecutorService?

As I understand Handler and ScheduledExecutorService is only for relative time, right?

like image 233
pvllnspk Avatar asked Nov 09 '12 21:11

pvllnspk


People also ask

What is a timer handler?

The Java TimerTask and the Android Handler both allow you to schedule delayed and repeated tasks on background threads. However, the literature overwhelmingly recommends using Handler over TimerTask in Android (see here, here, here, here, here, and here).

Where are Threadpoolexecutor and TimerTask used?

According to Java Concurrency in Practice: Timer can be sensitive to changes in the system clock, ScheduledThreadPoolExecutor isn't. Timer has only one execution thread, so long-running task can delay other tasks. ScheduledThreadPoolExecutor can be configured with any number of threads.


1 Answers

All three allow you to execute tasks on a different (eg. non-main) thread. The Handler allows you to use a message passing Actor pattern to communicate safely between thread. It does not allow you to do timing/delays/etc.

A ScheduledExecutorService is a very generic threading management solution. You initialize it with a certain number to worker threads and then give it work units. You can delay/time and repeat work units.

The Timer class has a simple API which resembles a ScheduledExecutorService for one-time, one-thread usage. The official API suggests to not use this class but roll your own ScheduledExecutor instead.

like image 147
Max Hille Avatar answered Oct 13 '22 06:10

Max Hille