2009-06-24 94 views
2

我有一個Java Web應用程序,它與文件約定有很大關係。
我正在使用Tomcat 6作爲我的servlet容器。當提交很多請求時,Tomcat變得非常飢餓。我想知道如何微調tomcat來減少內存消耗。 我也在考慮改變我的servlet容器。
你有什麼建議?調整Tomcat內存和CPU消耗

+0

你是什麼意思 「的工作很多與文件約定」 是什麼意思? – 2009-06-24 06:35:44

回答

4

您可以限制conf/server.xml配置中的接受/操作連接數量。

<Executor name="tomcatThreadPool" namePrefix="catalina-exec-" 
    maxThreads="16" minSpareThreads="1"/> 

<Connector executor="tomcatThreadPool" 
      port="8080" protocol="HTTP/1.1" 
      connectionTimeout="20000" 
      redirectPort="8443" 
      /> 

<Connector port="8080" protocol="HTTP/1.1" 
      connectionTimeout="20000" 
      redirectPort="8443" 
      maxThreads='16'/> 
在配置文件

,這應該制動你。

編輯:基於您的評論,你可以將處理轉移到根據您的CPU計數(Runtime.getRuntime().availableProcessors())大小的專用線程池(見ExecutorServiceExecutors)。然後,你可以申請一個有界LinkedBlockingQueue節流未決的數量任務(不要忘記指定一個RejectedExecutionHandler在隊列滿時執行阻塞添加)。

編輯2:添加到類的鏈接。你可以找到一些樣品。

編輯3:我在項目中使用的示例方法。

/** 
* Creates a new thread pool based on some attributes 
* @param poolSize the number of worker threads in the thread pool 
* @param poolName the name of the thread pool (for debugging purposes) 
* @param priority the base priority of the worker threads 
* @param capacity the size of the task queue used 
* @return the ExecutorService object 
*/ 
private ExecutorService newPool(int poolSize, 
String poolName, final int priority, int capacity) { 
    int cpu = Runtime.getRuntime().availableProcessors(); 
    ExecutorService result = null; 
    if (poolSize != 0) { 
     if (poolSize == -1) { 
      poolSize = cpu; 
     } 
     if (capacity <= 0) { 
      capacity = Integer.MAX_VALUE; 
     } 
     result = new ThreadPoolExecutor(poolSize, poolSize, 
       120, TimeUnit.MINUTES, 
       new LinkedBlockingQueue<Runnable>(capacity), 
     new ThreadFactory() { 
      @Override 
      public Thread newThread(Runnable runnable) { 
       Thread t = new Thread(runnable); 
       t.setPriority(priority); 
       return t; 
      } 
     }, new RejectedExecutionHandler() { 
      @Override 
      public void rejectedExecution(Runnable r, 
        ThreadPoolExecutor executor) { 
       if (!executor.isShutdown()) { 
        try { 
         executor.getQueue().put(r); 
        } catch (InterruptedException ex) { 
         // give up 
        } 
       } 
      } 
     }); 
    } 
    return result; 
} 

而且你可以使用這種方式:

ExecutorService exec = newPool(-1, "converter pool", Thread.NORM_PRIORITY, 500); 
servletContext.setAttribute("converter pool", exec); 

而且在你的servlet

ExecutorService exec = (ExecutorService)servletContext 
.getAttribute("converter pool"); 

exec.submit(new Runnable() { 
    public void run() { 
     // your code for transformation goes here 
    } 
}