Check if there is enough memory to allocate a byte array

I need to load a file into memory. Before I do this, I want to make sure that there is enough memory left on my virtual machine. If not, I would like to show an error message. I want to avoid an exception OutOfMemory.

an approach:

  • Get file size of my file
  • Use Runtime.getRuntime().freeMemory()
  • Check if it fits

Will this work or do you have other suggestions?

+4
source share
3 answers

The problem with any “check first and then do” strategy is that there may be changes between “check” and “do” that make the whole thing useless.

", " , , . "check first", , .

. - , , , .

, , . Java , -, , (, ).


, , , , , . 400M, 600, , 400M.

, (, 600 1M), , 400. , 400 .

, , , , , . , . , .

, , , (, 100M 10% - ), . . - , , .

+5

, - .

+1

FileChannel.map(FileChannel.MapMode, long, long). (, POSIX mmap) . (, ) .

+1

All Articles