Keep pushing the msg at regular interval may cause overflow at the endpoint if for some reason endpoint become slow Hence I think you should consider throttling of pushing request as well instead of blindly pushing the requests at regular interval. Based on all such requirements I think you can opt for ExecutorService, Instead of TimerTask or low level thread approach. Example of ExecutorService http://tutorials.jenkov.com/java-util-concurrent/executorservice.html
Performance considerations for Thread.sleep() and schedulerExecutorService.scheduleWithFixedDelay
-
17-06-2023 - |
Вопрос
I am trying to write a daemon thread for polling which will poll every "3" seconds. I've seen 3 approaches. I am not sure which one to go for ? I want to know the performance considerations. Which one could be consistant and will take smaller memory chunk ?
Approach 1 : Using the TimerTask ( Not planning to use this )
new Timer().scheduleAtFixedRate(task, firstTime, period)
Approach 2 : Using ScheduledExecutorService
Approach 3 : Using Thread.sleep() ....
If I boil down to code its something like this :
Approach #2
public class Test {
static TimerTask timerTask = new TimerTask() {
@Override
public void run() {
// Do polling & Other business logic
System.out.println("=="+new Date());
}
};
public static void main(String[] args) {
ScheduledExecutorService scheduler = Executors
.newSingleThreadScheduledExecutor();
scheduler.scheduleWithFixedDelay(timerTask, 0, 3, TimeUnit.SECONDS);
}
}
For the
Approach #3
public class Test {
static Runnable task = new Runnable() {
@Override
public void run() {
while (true) {
try {
// Do polling & Other business logic
System.out.println("**"+new Date());
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
public static void main(String[] args) {
new Thread(task).start();
}
}
According to my understanding threadpools are kind of heavy objects compared to normal threads. I want to know what are the pros and cons of using either of these approaches ?
Thanks in advance.
Regards, JE
Решение
Не связан с StackOverflow