简体   繁体   中英

Why does InputStream read method block the resource?

Why does InputStream's read method block the resource when there's nothing to read?

Let's say I've a RandomAccessFile opened in RW mode, and I create InputStream / OutputStream using File Descriptor.

Thread 1 is trying to read from the file, while nothing is available. At this time, if thread 2 tries to write to the file, it's blocked.

Why is that so?

The FileDescriptor is the object carrying the OS file handle, which means it's the object carrying the file pointer.

Only one thread can use the file handle / file pointer at a time, because a FileDescriptor does not support multi-threading. Access has been synchronized.

If you want two threads to have independent access to the file, then you need two FileDescriptors.

To prove my point of shared file pointer, what do you think would happen if you alternately read from FileInputStream and write to FileOutputStream ?

Here is code to show what happens:

String fileName = "Test.txt";
Files.writeString(Paths.get(fileName), "abcdefghijklmnopqrstuvwxyz", StandardCharsets.US_ASCII);

try (RandomAccessFile raFile = new RandomAccessFile(fileName, "rw");
     FileInputStream in = new FileInputStream(raFile.getFD());
     FileOutputStream out = new FileOutputStream(raFile.getFD()) ) {

    byte[] buf = new byte[4];
    for (int i = 0; i < 3; i++) {
        int len = in.read(buf);
        System.out.println(new String(buf, 0, len, StandardCharsets.US_ASCII));

        out.write("1234".getBytes(StandardCharsets.US_ASCII));
    }
}

String s = Files.readString(Paths.get(fileName), StandardCharsets.US_ASCII);
System.out.println(s);

Output

abcd
ijkl
qrst
abcd1234ijkl1234qrst1234yz

As you can see, reading 4 bytes returns bytes 0-3 and moves the file pointer, so writing of 4 bytes replaces bytes 4-7, then reading 4 bytes returns bytes 8-11, and writing of 4 bytes replaces bytes 12-15, and so forth.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM