'How does I/O-methods like read() put a Thread in blocked state in java?

So, if i have understood this correctly, a thread goes into waiting state when we call wait on an object and it goes into blocked state when it is waiting for a lock on an object(like when trying to get into a synchronized block or method).

How does I/O-methods like read() put a Thread in a blocked state though? I understand WHY it has to be in a blocked state, waiting for data that it can read but i'm also interested in HOW. How does the JVM notify the thread that it can continue when data in the resource its trying to read, is available again?



Solution 1:[1]

This depends on the native platform.

In POSIX, a call to read usually blocks until data is available, but there are many other reasons to return, such as an end-of-file was reached, the file descriptor was closed, the operation timed out or a signal interrupted the operation.

In Windows, the most closely related function is ReadFile.


The gory details, refering to Java 8 update 112 b15:

FileInputStream.read calls the native FileInputStream.read0, implemented natively through JNI in Java_java_io_FileInputStream_read0, which calls readSingle, which calls IO_Read.

In POSIX, IO_Read is defined as handleRead, which calls read. The RESTARTABLE macro loops while there's an error and the errno is EINTR.

In Windows, IO_Read is defined as handleRead, which calls ReadFile.

Solution 2:[2]

ptr is just a variable that should hold an address to a Nokta object. But you did not create a Nokta object for the pointer to point to.

Nokta noktaObj = Nokta(someNum, someNum)

Nokta* ptr = &noktaObj

When you don't initialize the object, and try to access data (like ptr->getX()), you're just getting whatever garbage happens to be in memory in that location.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2