user2742371
user2742371

Reputation:

Repeating threads with loops vs repeating runnable with scheduleAtFixedRate()

final Runnable refresh = new Refresh(params...);
service = Executors.newScheduledThreadPool(1);
service.scheduleAtFixedRate(refresh, 0, 2000, TimeUnit.MILLISECONDS);

// OR

final Thread refresh = new Refresh(params...);
refresh.start(); // In the run() method there is a loop with a sleep of 2000 ms

Which of the above methods to repeat a piece of code are preferred and why?

Upvotes: 1

Views: 765

Answers (2)

Daniel Nuriyev
Daniel Nuriyev

Reputation: 643

  1. scheduling at fixed rate is not the same as sleeping. scheduleAtFixedRate calls run every n milliseconds after the start of the previous execution, whereas sleep will start sleeping after the end of the previous execution and thus every following execution will be delayed by the time it took to run. Therefore you should either use scheduleWithFixedDelay or measure the time it takes to run and extract from the sleep time
  2. Using an ExecutorService is better for miltiple reasons. First, as assylias has mentioned, you separate the code from how you choose to run it. Second, an ExcutorService has additional code for managing a thread's lifecycle, execution and priority.
  3. If you using 1 thread, take a look at Timer and TimerTask

Upvotes: 0

assylias
assylias

Reputation: 328568

It is functionally equivalent but the former is more flexible and better separate responsibilities (SRP): a task should not be responsible for how or when it's run...

Upvotes: 1

Related Questions