我有一些旧代码,之前可以正常工作,但现在在使用OpenJDK 6的新服务器上运行时似乎出了问题,而不是Java SE 6。
问题似乎围绕着JAI.create展开。我有一些jpeg文件,我将它们缩放并转换为png文件。这段代码以前可以正常工作且没有泄漏,但现在在迁移到运行OpenJDK的服务器上后,文件描述符似乎永远不会关闭,并且我看到越来越多的tmp文件在服务器的tmp目录中积累。这些不是我创建的文件,所以我认为是JAI创建的。
另一个原因可能是新服务器上较大的堆大小。如果JAI在finalize时进行清理,但GC发生的频率较低,则可能会因此导致文件积累。减小堆大小不是一个选项,而我们似乎遇到了与增加ulimit无关的问题。
以下是运行此代码时出现泄漏的文件示例:
/tmp/imageio7201901174018490724.tmp
一些代码:
// Processor is an internal class that aggregates operations
// performed on the image, like resizing
private byte[] processImage(Processor processor, InputStream stream) {
byte[] bytes = null;
SeekableStream s = null;
try {
// Read the file from the stream
s = SeekableStream.wrapInputStream(stream, true);
RenderedImage image = JAI.create("stream", s);
BufferedImage img = PlanarImage.wrapRenderedImage(image).getAsBufferedImage();
// Process image
if (processor != null) {
image = processor.process(img);
}
// Convert to bytes
bytes = convertToPngBytes(image);
} catch (Exception e){
// error handling
} finally {
// Clean up streams
IOUtils.closeQuietly(stream);
IOUtils.closeQuietly(s);
}
return bytes;
}
private static byte[] convertToPngBytes(RenderedImage image) throws IOException {
ByteArrayOutputStream out = null;
byte[] bytes = null;
try {
out = new ByteArrayOutputStream();
ImageIO.write(image, "png", out);
bytes = out.toByteArray();
} finally {
IOUtils.closeQuietly(out);
}
return bytes;
}
我的问题是:
- 有人遇到过这个问题并解决了吗?由于创建的临时文件不是我的,所以我不知道它们的名称,因此无法处理它们。
- 哪些图像调整和重新格式化库是首选?我听说过Scalr - 还有其他什么值得我研究的吗?
我目前不想重写旧代码,但如果没有其他选择......
谢谢!