I have a snipper code below to upload a file to another storage. It works properly with files < 1GB of data. However, it exposes "OutOfMemoryError: Java heap space" exception with files size > 1GB (I verified with 1.2GB and 1.5GB)
After searching some posts, I increase the JVM Heap Space to 8GB. But, I still see the exception.
My machine is 16GB of RAM
The JVM version and Java Runtime Environment settings as below

Here is the snippet code:
protected boolean uploadFile(File file) throws BaseAFException {
try (RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r");
FileChannel channel = randomAccessFile.getChannel();
FileLock lock = channel.lock(0, Long.MAX_VALUE, true)) {
PayloadMessage payload = new PayloadMessage();
try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
int bufferSize = 1024;
if (bufferSize > channel.size()) {
bufferSize = (int) channel.size();
}
ByteBuffer buff = ByteBuffer.allocate(bufferSize);
while (channel.read(buff) > 0) {
out.write(buff.array(), 0, buff.position());
buff.clear();
}
//the exception exposes before the debugger hits the line below
payload.setContent(out.toByteArray());
}
//Upload file will be handled here
return true;
} catch (OverlappingFileLockException e) {
return false;
} catch (Exception e) {
throw new Exception("Could not upload file " + file.getAbsolutePath(), e);
}
}
The exception stack trace:
Throwable : java.lang.OutOfMemoryError: Java heap space java.util.concurrent.ExecutionException: java.lang.OutOfMemoryError: Java heap space
at java.util.concurrent.FutureTask.report(Unknown Source)
at java.util.concurrent.FutureTask.get(Unknown Source)
at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.OutOfMemoryError: Java heap space
at java.util.Arrays.copyOf(Unknown Source)
at java.io.ByteArrayOutputStream.grow(Unknown Source)
at java.io.ByteArrayOutputStream.ensureCapacity(Unknown Source)
at java.io.ByteArrayOutputStream.write(Unknown Source)
I would greatly appreciate it if you kindly give me some advice!