Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Buffer size in Java

Tags:

java

file

io

buffer

I have got a little question about buffer size in Java. Why do we set buffer size to 1024 or 2^n. For example:

    inputStream = file.getInputStream();
    File newFile = new File("C:/uploads/operators.xml");
    outputStream = new FileOutputStream(newFile);
    int read = 0;

    byte[] bytes = new byte[1024];
    while ((read = inputStream.read(bytes)) != -1) {
        outputStream.write(bytes, 0, read);
    }
    outputStream.close();
    inputStream.close();

How outputStream.write(bytes, 0, read); works? Why do we use bytes array?

like image 711
Tony Avatar asked Oct 21 '22 14:10

Tony


1 Answers

To avoid wasting hit to file system, byte sizes should be a multiple of file system sector size (e.g. 512 bytes).

Same applies to CPU L1 cache. Most Intel 486 CPUs has 1K L1 cache, thus the value 1024. Pentium CPUs have at least 8K L1 cache, thus 8 * 1024 is also often used.

Recent file systems have a sector size of 4K and recent CPUs have at least 64K L1 Cache, thus 64 * 1024 is also a choice.

like image 55
weakish Avatar answered Oct 23 '22 05:10

weakish