Java Jetty内存使用情况

时间:2012-07-28 20:32:20

标签: java servlets jetty

我正在运行Jetty Web服务器并使用它来执行一些bash脚本,具体取决于它通过GET接收的参数。我从来没有和Jetty合作过,所以我把一些东西from here拼凑起来让它运转起来。我的问题是,当没有请求时,它在~100mb的内存中空闲,大约12小时后,它就会高达1gb内存。如果请求是合法的,那么对于只运行bash脚本的东西来说,这似乎是非常糟糕的。 servlet最终服务的平均文件大小约为400kb。

服务器的启动方式:

public void startServer() {

    String hostname = "localhost";
    int port        = 7500;

    Server server = new Server();

    Connector connector = new SelectChannelConnector();
    connector.setHost(hostname);
    connector.setPort(port);

    server.setConnectors(new Connector[]{connector});
    server.setStopAtShutdown(true);

    ServletContextHandler context = new ServletContextHandler();
    context.setContextPath("/");
    context.addServlet(new ServletHolder(new DaemonServlet()), "/call/*");

    HandlerList handlers = new HandlerList();
    handlers.setHandlers(new Handler[] { context });

    server.setHandler(handlers);
    server.start();
    server.join();
}

servlet(DaemonServlet):

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {

    String msg = "";

    String call = request.getParameter("call");
    ProcessBuilder pb = null;
    Process p = null;

    switch (call) {
    case "sendAction": // Sends an action to a process with a certain ID
        pb = new ProcessBuilder("/bin/bash", "/opt/test/process.sh", request.getParameter("process"), request.getParameter("action"));
        break;
    case "getFile": // Reads the file with the given ID into a string, to be returned by Jetty
        pb = new ProcessBuilder("/bin/bash", "/opt/test/getFile.sh", request.getParameter("fileId"));
        try {
            p = pb.start();
            BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String scriptOutput = "";
            String line;
            while ((line = br.readLine()) != null) {
                scriptOutput += line + '\n';
            }
            br.close();
            msg = scriptOutput;
            p.destroy();
            p = null;
        } catch (Exception e) {}
        break;
    }

    response.setContentType("text/html");
    response.setStatus(HttpServletResponse.SC_OK);
    response.getWriter().println(msg);
}

这里似乎有什么不正确的设置吗?

2 个答案:

答案 0 :(得分:0)

看起来就像这一行:

scriptOutput += line + '\n';

耗费了大量内存。为什么不在收到回复时通过回复写回信息呢?

答案 1 :(得分:0)

正如Reimeus所说,你应该在你得到它时回应输出。如果你这样做,你应该在发送流程输出之前发送响应标题(内容类型,状态代码)

至少,您应该use StringBuilder instead of concatenating Strings