In my application, I have written a REST call which would be used by developers and support persons only, where it loads data of n size from the logs file and return it as text/plain, where n is a configurable number which cannot be more than fixed size.
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);
Now here is my question, we know that String are immutable and any new String created goes into String pool never to be cleaned till JVM is on and running. So in that case every time this REST call is made would not it be a hit on memory in the sense that it would keep loading large text into String pool?
If yes, what are the alternatives, I can't pass the byte array as that would be unreadable. How can it be better?
Update : Please note that this question is not about new constructor of String or literal representation, It is about how it can be optimized to avoid the large String being stored into string pool with or without a reference from heap object.