2012-12-05 36 views
0

我想用我定義的屬性初始化Synchronized static singleton ThreadPool Executor。初始化服務器啓動時的同步ThreadPool執行程序

我希望它在整個應用程序中都可用,並且應該在服務器重新啓動或停止時銷燬。

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; 
    } 

這是我迄今爲止所做的(我是多線程的新手)。

由於我的應用程序完全基於多線程,我該如何實現我的要求和任何需要改進的地方! 正如我所說,我如何維護/使其通過應用程序可用。

+0

什麼是您的服務器?它有啓動和關閉掛鉤嗎? – reprogrammer

+0

Tomcat 7,它也將部署在Jboss 7中 – Reddy

+0

這個問題類似於http://stackoverflow.com/q/1549924/130224 – reprogrammer

回答

2

使用實現在web.xmlServletContextListener類:

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

ThreadPoolManager應該覆蓋的方法contextInitilized(ServletContextEvent)contextDestroyed(ServletContextEvent)。調用Web應用程序初始化過程的方法contextInitilized(ServletContextEvent)正在啓動。所以,你應該在那裏做你的初始化工作。同樣,當servlet上下文即將關閉時,方法contextDestroyed(ServletContextEvent)被調用。所以,你應該在那裏做清理工作。

+0

我已經做了同樣的事情 public class MyListener實現ServletContextListener {0}私有靜態ThreadPoolExecutor threadPoolExecutor = ThreadPoolExecutor.getInstance(); //某些代碼 } 這樣好嗎? – Reddy

+0

您應該在覆蓋接口方法的方法中執行初始化和清理工作。查看我更新的答案以獲取更多詳情。 – reprogrammer

相關問題