1
votes

I have the following config for ThreadPoolTaskExecutor

 <bean id="threadPoolTaskExecutor" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
    <property name="corePoolSize" value="10" />
    <property name="maxPoolSize" value="25" />
    <property name="queueCapacity" value="30" />
</bean>

and I have 2 methods in my public class AdminService.

  1. void triggerJob();
  2. boolean executeSql(String sql);

How do i insert ThreadPoolTaskExecutor into triggerJob method so it creates new thread when executeSql is called inside first method.

Inside triggerjob i have loop that calls executeSql based on condition.

Do i need to create a private class that implements runnable so ThreadPoolTaskExecutor can execute this class or is it possible to create threads without runnable ?

My idea is something like this

@Autowired    
ThreadPoolTaskExecutor threadPoolTaskExecutor;

     void triggerJob(){
           for( Object k:Objects){
               if(k.equals(something){
                //here new thread to be created somehow 
                threadPoolTaskExecutor.execute(executeSql(k.getSql())
               }
           }
        }
1
Why do you need new thread? What's wrong with reusing threads? This is exactly what thread pool is intended for. - M. Prokhorov
@M.Prokhorov the task is executeSql to be executed in new Thread but i don't know much about threads so not sure how to implement this - Master Yi
Why it has to be a new Thread? - M. Prokhorov

1 Answers

1
votes

If you have to do it you can use org.springframework.core.task.SimpleAsyncTaskExecutor:

<bean id="simpleTaskExecutor" class="org.springframework.core.task.SimpleAsyncTaskExecutor">
   <property name="concurrencyLimit" value="25" />
</bean>

But creating a Java thread is expensive. It's generally recommended to reuse threads, even SimpleAsyncTaskExecutor docs say:

NOTE: This implementation does not reuse threads! Consider a thread-pooling TaskExecutor implementation instead, in particular for executing a large number of short-lived tasks.