调整Tomcat的内存和CPU消耗

3

我有一个与文件约定密切相关的Java Web应用程序。
我使用Tomcat 6作为我的Servlet容器。当提交了许多请求时,Tomcat会变得非常占用内存。我想知道如何对Tomcat进行微调以减少内存消耗。
我也在考虑更改我的Servlet容器。
你有什么建议吗?


“working a lot with file conventions” 是什么意思? - Jon Skeet
1个回答

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 and Executors)。然后,您可以应用有界的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
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接