【发布时间】:2017-01-07 08:19:55
【问题描述】:
在我的应用程序中,我编写了一个 REST 调用,仅供开发人员和支持人员使用,它从日志文件加载 n 大小的数据并将其作为文本/纯文本返回,其中 n 是一个可配置的数字,不能超过固定大小。
RandomAccessFile file = new RandomAccessFile(logFinalPath, "r");
//chunk default is 100000 max is 500000
chunk = chunk <=0l?100000:(chunk>500000?500000:chunk);
long fileSize = file.length();
//start position is either chunk size from the end or when the file is smaller then from the beginning of file
long pos = fileSize>chunk?file.length()-chunk:0;
int maxSize = (int) (fileSize>chunk?chunk:fileSize);
file.seek(pos);
byte[] bytes = new byte[maxSize];
file.read(bytes);
file.close();
logger.info("fileSize : "+fileSize);
return new String(bytes);
现在这是我的问题,我们知道 String 是不可变的,并且创建的任何新 String 都会进入 String 池,在 JVM 启动并运行之前永远不会被清理。因此,在这种情况下,每次进行此 REST 调用时,它不会对内存造成影响,因为它会不断将大文本加载到字符串池中?
如果是,有什么替代方案,我不能传递字节数组,因为那将是不可读的。怎样才能更好?
更新:请注意,这个问题不是关于字符串的新构造函数或文字表示,而是关于如何优化它以避免将大字符串存储到字符串池中,无论是否有来自堆对象的引用。
【问题讨论】:
标签: java string memory memory-management jvm