0

I want to initialize Synchronized static singleton ThreadPool Executor with my defined properties.

I want it to available through out the application and should be destroyed when server is restarted or stopped.

public class ThreadPoolExecutor extends java.util.concurrent.ThreadPoolExecutor {
    private static Properties properties;
    static {
        try {
            properties.load(ThreadPoolExecutor .class.getClassLoader().getResourceAsStream("config.properties"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    static final int defaultCorePoolSize = Integer.valueOf((String) properties.get("CORE_POOL_SIZE"));
    static final int defaultMaximumPoolSize = Integer.valueOf((String) properties.get("MAX_POOL_SIZE"));
    static final long defaultKeepAliveTime = Integer.valueOf((String) properties.get("KEEP_ALIVE_TIME"));
    static final TimeUnit defaultTimeUnit = TimeUnit.MINUTES;
    static final BlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<Runnable>();
    private static ThreadPoolExecutor instance;

    private ThreadPoolExecutor() {
        super(defaultCorePoolSize, defaultMaximumPoolSize, defaultKeepAliveTime, defaultTimeUnit, workQueue);
    }

    synchronized static ThreadPoolExecutor getInstance() {
        if (instance == null) {
            instance = new ThreadPoolExecutor();
        }
        return instance;
    }   

This is what I have done till now (I am newbie to Multi-threading).

As my application is completely based on Multi-threading, how do I achieve my requirements and anything to improve here! As I said, how do i maintain/make it available through out the application.

RaceBase
  • 18,428
  • 47
  • 141
  • 202

1 Answers1

2

Use a class that implements ServletContextListener in your web.xml:

<web-app>
    <!-- ... -->
    <listener>
        <listener-class>com.domain.ThreadPoolManager</listener-class>
    </listener>
</web-app>

The class ThreadPoolManager should override the methods contextInitilized(ServletContextEvent) and contextDestroyed(ServletContextEvent). The method contextInitilized(ServletContextEvent) gets invoked the web application initialization process is starting. So, you should do your initialization work there. Similarly, the method contextDestroyed(ServletContextEvent) gets invoked when the servlet context is about to be shut down. So, you should do your clean up work there.

reprogrammer
  • 14,298
  • 16
  • 57
  • 93
  • I have done the samething public class MyListener implements ServletContextListener { private static ThreadPoolExecutor threadPoolExecutor = ThreadPoolExecutor.getInstance(); //SOME CODE } is this fine? – RaceBase Dec 05 '12 at 15:19
  • You should do the initialization and cleanup work in the methods that override methods of the interface. See my updated answer for more details. – reprogrammer Dec 05 '12 at 16:36