gpt4 book ai didi

java - Spring 4 TaskScheduler 性能问题

转载 作者:搜寻专家 更新时间:2023-11-01 03:18:20 25 4
gpt4 key购买 nike

我正在为贸易自动化网站构建 Spring 4 Rest API。

在服务层中,使用 Spring TaskScheduler.schedule(Runnab‌ le arg0, Date arg1) 接口(interface)动态创建一个 cronjob,它将创建一个 Runnable,在作为参数给定的时间执行,恰好一次。该线程将调用另一个服务来访问我的 Hibernate DAO 层并在将来做一些事情。

配置类和实现如下。

@Configuration
@EnableWebMvc
@EnableScheduling
@ComponentScan("com.example")
public class SpringMvcConfig extends WebMvcConfigurerAdapter {
@Bean
public ThreadPoolTaskScheduler taskScheduler() {
return new ThreadPoolTaskScheduler();
}
}


@Service
public class TransactionServiceImp implements TransactionService {

@Autowired
private TaskScheduler scheduler; //org.springframework.scheduling.TaskScheduler;
@Autowired
private TaskExecutorService taskService; //My service

@Transactional
public myFunction(){

//some code

final Long key = //some id value from db
Date exeTime = //some java.util.Date in future

Runnable runnable = new Runnable() {

private long id = key;
public void run() {
taskService.doSomething(id);
}
};
ScheduledFuture<?> sheduler = scheduler.schedule(runnable, exeTime);

//some code
}
}

此代码运行良好,在准确的时间和恰好一次执行任务。

通过eclipse调试,发现每次调用scheduler.schedule()都会创建一个新的daemon线程(处理http请求到spring mvc时) .我的问题是,

  1. Is my thinking correct that jvm creates new daemon thread on each scheduler.schedule() call (Rather than creating thread at the date-time specified) ?

  2. The created daemon threads are still showing Running status in Eclipse debug even after the task executed. Will the thread be destroyed or not on finishing run() method ?

  3. Else, will it be a performance issue ?

最佳答案

ThreadPoolTask​​Scheduler 包装 ScheduledThreadPoolExecutor (一个底层的 jdk 实现),线程可以从一组预定义的工作线程中重用。每个任务都分配/处理到工作队列。

even core threads are initially created and started only when new tasks arrive

jvm 在每次调用 scheduler.schedule() 时创建新的守护线程(而不是在指定的日期时间创建线程),我的想法是否正确?

你每次都在创建线程实例(Runnable),因为它接受可运行的,因此你的任务应该被执行或者队列中现有的工作线程可能是空闲的。如果达到最大池大小,您的任务将等待。

即使在任务执行后,创建的守护线程在 Eclipse 调试中仍显示运行状态。在完成 run() 方法时线程是否会被销毁?

Java 文档是这样说的,

Execution will end once the scheduler shuts down or the returned ScheduledFuture gets cancelled.

否则,会不会是性能问题?可以运行的最大最佳线程数受 cpu 内核的限制。所以增加池大小不一定会提高性能

https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ScheduledThreadPoolExecutor.html

关于java - Spring 4 TaskScheduler 性能问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39888535/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com