当前位置: 动力学知识库 > 问答 > 编程问答 >

scheduledexecutorservice - Java SchedulerExecutor

问题描述:

Recently I wrote code that had to limit request throughput. I used ScheduleExecutorService.scheduleAtFixedRate and I believed that it should do the work (It did!) but I wrote some test to check time of scheduled task and i was amazed. First few tasks weren't scheduled as javadoc explain with n*period. Can anyone explain me what am I missing?

If it work that way then why it is not mentioned in javadoc? And then question is how exactly scheduler work?

I would like to avoid looking into sources:)

Example:

import java.time.Duration;

import java.time.LocalTime;

import java.time.temporal.ChronoUnit;

import java.util.concurrent.BlockingQueue;

import java.util.concurrent.Executor;

import java.util.concurrent.Executors;

import java.util.concurrent.LinkedBlockingQueue;

import java.util.concurrent.ScheduledExecutorService;

import java.util.concurrent.TimeUnit;

public class ExecutorTest {

Executor executor;

ScheduledExecutorService schedulingExecutor;

BlockingQueue<LocalTime> times;

public static void main(String[] args) throws InterruptedException {

new ExecutorTest().start();

}

public ExecutorTest() {

schedulingExecutor = Executors.newScheduledThreadPool(1);

executor = Executors.newCachedThreadPool();

times = new LinkedBlockingQueue<>();

}

public void start() throws InterruptedException {

schedulingExecutor.scheduleAtFixedRate(this::executeTask, 0, 50, TimeUnit.MILLISECONDS);

LocalTime nextEvaluatedTime = times.take();

LocalTime time = nextEvaluatedTime;

while (true) {

System.out.println(String.format(String.join(" ", "recorded time: %d", "calculated proper time: %d", "diff: %d"),

time.toNanoOfDay(),

nextEvaluatedTime.toNanoOfDay(),

Duration.between(nextEvaluatedTime, time).toNanos()));

nextEvaluatedTime = time.plus(50, ChronoUnit.MILLIS);

time = times.take();

}

}

private void executeTask() {

executor.execute(() -> {

times.add(LocalTime.now());

});

}

}

If you run this program you could see that few first time wasn't recorded as expected. Why?

分享给朋友:
您可能感兴趣的文章:
随机阅读: