Complete the code to define a thread pool bean with a fixed size of 5 threads.
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; @Configuration public class ThreadPoolConfig { @Bean public ExecutorService taskExecutor() { return Executors.[1](5); } }
The newFixedThreadPool method creates a thread pool with a fixed number of threads, which is 5 here.
Complete the code to set the core pool size of the ThreadPoolTaskExecutor to 10.
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; @Configuration public class ThreadPoolConfig { @Bean public ThreadPoolTaskExecutor taskExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize([1]); return executor; } }
The setCorePoolSize method sets the number of core threads to 10 as required.
Fix the error in the code by completing the missing method to initialize the executor.
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; @Configuration public class ThreadPoolConfig { @Bean public ThreadPoolTaskExecutor taskExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(5); executor.setMaxPoolSize(10); executor.[1](); return executor; } }
The initialize() method initializes the ThreadPoolTaskExecutor so it is ready to use.
Fill both blanks to configure the thread name prefix and queue capacity.
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; @Configuration public class ThreadPoolConfig { @Bean public ThreadPoolTaskExecutor taskExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setThreadNamePrefix([1]); executor.setQueueCapacity([2]); return executor; } }
The thread name prefix is set to "MyPool-" to identify threads easily. The queue capacity is set to 50 to hold tasks waiting for execution.
Fill all three blanks to set core pool size, max pool size, and keep alive seconds.
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; @Configuration public class ThreadPoolConfig { @Bean public ThreadPoolTaskExecutor taskExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize([1]); executor.setMaxPoolSize([2]); executor.setKeepAliveSeconds([3]); return executor; } }
The core pool size is set to 10, max pool size to 15, and threads will be kept alive for 60 seconds when idle.