Julian Korkosz
Julian Korkosz

Reputation: 11

Possibility of memory leak in method

This is my method, I want to know if there is possibility for memory leak? If there is what should I do to?

private byte[] getNewContent(String filePath, int position, int size) throws IOException {
    RandomAccessFile file = new RandomAccessFile(filePath, "r");
    file.seek(position);
    byte[] bytes = new byte[size];
    file.read(bytes);
    file.close();
    return bytes;
}

Upvotes: 1

Views: 51

Answers (1)

Iłya Bursov
Iłya Bursov

Reputation: 24229

yes, there is resource leak

if some exception happens in seek/read methods - file will not be closed, it is better to use try-with-resources idiom:

private byte[] getNewContent(String filePath, int position, int size) throws IOException {
    try (RandomAccessFile file = new RandomAccessFile(filePath, "r")) {
        file.seek(position);
        byte[] bytes = new byte[size];
        file.read(bytes);
        return bytes;
    }
}

this way file will be closed no matter what

Upvotes: 1

Related Questions