Java heartbeat: timerTask or thread.sleep ()?

I want to implement a very simple client server in Java. The easiest approach seems to be a dream. Consider metacode below.

class MyClass Thread heartbeatThread = new Thread(); public void() startHeartBeat{ Thread.sleep(4000); sock.write("H"); } 

Is this an adequate solution, or are there pitfalls that I do not consider?

I also considered using the java.util.Timer.scheduleAtFixedRate approach. Will it be more reliable / reliable? If so, why? Here is an example (this is not so pure IMO):

 class HeartBeat { Timer timer=new Timer(); public void scheduleHeartBeat(int delay, int period) { timer.scheduleAtFixedRate( new HeartBeatTask(), delay, period); } } class HeartBeatTaskextends TimerTask { public void run() { sock.write("H"); } 

Will the second approach be a higher priority?

+5
source share
3 answers

First, your Thread based idiom will not be scheduled at a fixed speed without an infinite loop.

This drawback too: you probably want to set some condition to exit the loop.

You also need to catch InterruptedException when calling static Thread.sleep .

Another popular idiom for scheduled execution is the ScheduledExecutorService .


Find the following 3 options:

Timer

 // says "foo" every half second Timer t = new Timer(); t.scheduleAtFixedRate(new TimerTask() { @Override public void run() { System.out.println("foo"); } }, 0, 500); 
  • Pros : Simple
  • Cons :

In a fixed-rate execution, each execution is planned relative to the planned execution time of the initial execution. If execution is delayed for any reason (such as garbage collection or other background activity), two or more executions will be executed in quick succession to “catch up”.

Docs are here .


Infinite loop

 new Thread() { @Override public void run() { while (true) { // Says "blah" every half second System.out.println("blah"); try { Thread.sleep(500); } catch (InterruptedException ie) { // nope } } } }.start(); 
  • Pros : super simple. You can periodically change your recurring delay.
  • Cons : Thread.sleep still

given the accuracy and accuracy of system timers and schedulers .... and requires catching an InterruptedException .

Docs are here .

also:

  • your infinite loop may require (somehow potentially cumbersome) violation of the condition
  • there is no initial delay setting if it is not applied manually until an infinite loop, which will require another try / catch .

Performers

 ScheduledExecutorService es = Executors.newSingleThreadScheduledExecutor(); es.scheduleAtFixedRate( new Runnable() { @Override public void run() { // Says "bar" every half second System.out.println("bar"); } }, 0, 500, TimeUnit.MILLISECONDS); 
  • Pros : This is the latest feature 3. Very simple and elegant - you can also schedule Callable (but not at a fixed speed) and reuse ExecutorService . The documentation for java.util.Timer actually mentions ScheduledThreadPoolExecutor (an implementation of the ScheduledExecutorService interface) as a "more universal replacement for the Timer / TimerTask combination."
  • Against as described:

If any execution of this task takes longer than its period, subsequent quotation marks may begin late,

Docs are here .

+10
source

If you are using a sleep approach, there are some issues to consider.

One of them is that the sleep time is not accurate, and you could get off over time (maybe while your thread is sleeping, another application starts the processor and it takes longer for your thread than expected in the next time the stream sends a pulse, it is delayed), your sleep time will be supplemented by various things gradually (you will not sleep less than your sleep time, but often can sleep a little more), and these increments will add up over time.

Another is that you may have a socket problem, you will have to write code to handle a new connection.

The stream must be good and responsive to interruption, or it must be a demon stream. If he needed to exchange data over streams, you would need to know the problems of memory visibility.

Using a timer means that every task start will have a new start and you will not be vulnerable to accumulated delays or outdated network connections.

+1
source

Yes, I don’t know how timers are implemented internally, but I understand that if you use sleep, you will have to handle InterruptedException, and there is an exception, this may not be good practice. in addition, timer tasks will work within their thread space, and you better control it.

You can stop the timer at any time if you wish. In this case, you cannot do it.

+1
source

Source: https://habr.com/ru/post/1244741/


All Articles