Executors creates a single thread pool Why there are two thread pools

@ Component
public class StatusListener implements ServletContextAware {

final ReentrantLock lock = new ReentrantLock();

@Override
public void setServletContext(ServletContext servletContext) {
    Runnable runnable = new Runnable() {
        public void run() {
            statusTask();
        }
    };

    ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();

    // 
    service.scheduleAtFixedRate(runnable, 20, 60, TimeUnit.SECONDS);
}

public void statusTask() {
    final ReentrantLock lock = this.lock;
    lock.lock();
    try {
        System.out.println(Thread.currentThread().getName());
        System.out.println(Thread.currentThread().getId());

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        lock.unlock();
    }
}

}

the running result is
pool-2-thread-1
40

pool-4-thread-1
42

Apr.05,2021

When the

spring initializes, the setServletContext method is called twice (or more times). Check out api, for yourself so the code above initializes more than one thread connection pool.
you can try it yourself, print a sentence in the setServletContext method and see how many times it has been executed.
notice the comments corresponding to api below.

public interface ServletContextAware extends Aware {

    /**
     * Set the {@link ServletContext} that this object runs in.
     * 

Invoked after population of normal bean properties but before an init * callback like InitializingBean's {@code afterPropertiesSet} or a * custom init-method. Invoked after ApplicationContextAware's * {@code setApplicationContext}. * @param servletContext ServletContext object to be used by this object * @see org.springframework.beans.factory.InitializingBean-sharpafterPropertiesSet * @see org.springframework.context.ApplicationContextAware-sharpsetApplicationContext */ void setServletContext(ServletContext servletContext); }

Menu