Cleanup renderStreaming to carry less state The close method only needs the tail of the template. Rewrite the closure so only the tail is retained as UTF-8 encoded bytes, allowing the JVM to free the larger String. Use try-with-resources to perform the final write. This ensures that if the write fails (e.g. stream is disconnected), the close still happens, and the risk of a file descriptor leaking is reduced. Change-Id: Ia694a3457a386fc311c702472f053d47e670a88c
diff --git a/gitiles-servlet/src/main/java/com/google/gitiles/Renderer.java b/gitiles-servlet/src/main/java/com/google/gitiles/Renderer.java index efeef9c..9face08 100644 --- a/gitiles-servlet/src/main/java/com/google/gitiles/Renderer.java +++ b/gitiles-servlet/src/main/java/com/google/gitiles/Renderer.java
@@ -165,23 +165,20 @@ OutputStream renderStreaming(HttpServletResponse res, String templateName, Map<String, ?> soyData) throws IOException { - final String html = newRenderer(templateName).setData(soyData).render(); + String html = newRenderer(templateName).setData(soyData).render(); int id = html.indexOf(PLACEHOLDER); checkArgument(id >= 0, "Template must contain %s", PLACEHOLDER); int lt = html.lastIndexOf('<', id); - final int gt = html.indexOf('>', id + PLACEHOLDER.length()); - final OutputStream out = res.getOutputStream(); + int gt = html.indexOf('>', id + PLACEHOLDER.length()); + + OutputStream out = res.getOutputStream(); out.write(html.substring(0, lt).getBytes(UTF_8)); out.flush(); + byte[] tail = html.substring(gt + 1).getBytes(UTF_8); return new OutputStream() { @Override - public void write(byte[] b) throws IOException { - out.write(b); - } - - @Override public void write(byte[] b, int off, int len) throws IOException { out.write(b, off, len); } @@ -198,8 +195,9 @@ @Override public void close() throws IOException { - out.write(html.substring(gt + 1).getBytes(UTF_8)); - out.close(); + try (OutputStream o = out) { + o.write(tail); + } } }; }