Issue
I have this async method in Spring Boot:
@Async
public void calculateResult(List matrix) {
//do calculation
}
This method is invoked at the controller.
I want to reduce the priority of this calculation method threads. How do I do that?
Solution
With async anotation u can not acheive this. @Async
take only custom task executor.. No way to set priority. But u can do it manualy like this:
Create this bean:
@Bean("CustomTaskExecutor")
public TaskExecutor threadPoolTaskExecutor(
@Value("${spring.async.core-pool-size}") int corePoolSize,
@Value("${spring.async.max-pool-size}") int maxPoolSize,
@Value("${spring.async.queue-capacity}") int queueCapacity) {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor() {
@Override
protected BlockingQueue<Runnable> createQueue(int queueCapacity) {
return new PriorityBlockingQueue<Runnable>(queueCapacity);
}
};
executor.setCorePoolSize(corePoolSize);
executor.setMaxPoolSize(maxPoolSize);
executor.setQueueCapacity(queueCapacity);
return executor;
}
Task with priorities:
public class Task implements Runnable {
private Consumer<Job> jobConsumer;
private Job job;
public Job getJob() {
return this.job;
}
public Task(Consumer<Job> jobConsumer, Job job) {
this.jobConsumer = jobConsumer;
this.job = job;
}
@Override
public void run() {
this.jobConsumer.accept(job);
}
}
Future custom task:
public class FutureCustomTask extends FutureTask<FutureCustomTask> implements Comparable<FutureCustomTask> {
private Task task;
public FutureCustomTask(Task task) {
super(task, null);
this.task = task;
}
@Override
public int compareTo(FutureCustomTask o) {
return task.getJob().getPriority().compareTo(o.task.getJob().getPriority());
}
}
Finaly set priority like this:
@Autowired
private TaskExecutor taskExecutor;
@Autowired
private JobBusiness jobBusiness;
...
Task task = new Task(jobBusiness::performSomethingOn, job);
taskExecutor.execute(new FutureCustomTask(task));
I took this answer from here
Look at this tutorial also....
Answered By - GolamMazid Sajib
Answer Checked By - Cary Denson (JavaFixing Admin)