Search code examples
springmultithreadingthreadpoolthreadpoolexecutor

How to make spring manage the thread of anonymous class


I understand that if I do following I can make spring manage the thread

@Component
@Scope("prototype")
public class ATask implements Runnable{....}
ThreadPoolTaskExecutor taskExecutor = (ThreadPoolTaskExecutor) context.getBean("taskExecutor");
ATask aTask1 = (ATask) ctx.getBean("aTask");
taskExecutor.execute(aTask1);

What I don't understand is what is the difference between

taskExecutor.execute(aTask1);

and

taskExecutor.execute(new ATask("A task 1"));

My guess is in second case, creation of thread is not managed by spring by execution is.

Second question, For below code,

this.taskExecutor.execute(new Runnable() {
       @Override
       public void run() {...}});

Does spring manage/control the number of threads run simultaneously? How do I make it work same as a thread with @Component and @Scope("prototype")? - One option is to move the code to a different class, but we are trying to avoid that as we have many small such methods.


Solution

  • Answer to your first question - there is no difference between first and second, in both the cases thread pool management will be handed by Spring because you are calling execute method on Spring's ThreadPoolTaskExecutor, if you were calling it on java.util.concurrent.ThreadPoolExecutor then thread pool management would not be handled by Spring.

    Answer to your second question - if you are using Spring's ThreadPoolTaskExecutor then thread pool management will be handled by Spring. You are read about core pool size, max pool size and queue capacity to understand how to control number of thread running simultaneously.

    Overall I think you are confused between the fact that Spring is fundamentally a IOC container and Spring provides ThreadPoolTaskExecutor for thread pool management (which is nothing but Spring's version of Java's java.util.concurrent.ThreadPoolExecutor).

    Understand it this way: when you do taskExecutor.execute(aTask1); then thread pool management will be handled by Spring because you are using Spring's ThreadPoolTaskExecutor, ALSO bean management will be handled by Spring because aTask1 is object of Spring bean. And when you do taskExecutor.execute(new ATask("A task 1")); then thread pool management will be handled by Spring because you are using Spring's ThreadPoolTaskExecutor, BUT this time bean management will not be done by Spring because you are using new to create object yourself.