调整Tomcat内存和CPU消耗

时间:2009-06-24 06:32:36

标签: java memory tomcat servlets performance

我有一个Java Web应用程序,它可以很好地处理文件约定 我使用Tomcat 6作为我的servlet容器。当提交了许多请求时,Tomcat变得非常渴望内存。我想知道如何微调tomcat以减少内存消耗。 我也在考虑更换我的servlet容器 你有什么建议?

1 个答案:

答案 0 :(得分: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())调整大小的专用线程池(请参阅ExecutorService和{{3}然后你可以应用一个有界Executors来限制挂起任务的数量(当队列满了时,不要忘记指定LinkedBlockingQueue来执行阻塞添加。)

编辑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
    }
}