Gimme the 411
Gimme the 411

Reputation: 1044

Is scala.io.StdIn.readLine() a blocking call?

Is scala.io.StdIn.readLine() a blocking call?

From the docs, there is no mention of it being a blocking call.

I want to do something like this:

while(true){
    val input = scala.io.StdIn.readLine()
    input match{
        case "quit" =>
            ...
        case "stats" =>
            ...
        case _ =>
            ...
    }
}

If it's not blocking, will it constantly loop, set input to null, and trigger case _ each time?

If it is blocking, why isn't it shown in the docs? Or where can I see a definition that says it is blocking?

In general, how can I know whether or not a method is blocking?

Upvotes: 1

Views: 689

Answers (1)

Mario Galic
Mario Galic

Reputation: 48420

how can I know whether or not a method is blocking?

Look at the return type of the method. If it is returning Future, IO, or some other effectful value F[A] that wraps a pure value A capable of modelling asynchronous computations, then assume it is non-blocking. For example consider

def f(v: Int): Future[Int] = Future(v + 1)
def g(v: Int): IO[Int] = IO(v + 1)

Here f and g are non-blocking in the sense of the thread that called them not being blocked until v + 1 is evaluated. On the other hand, if the method is returning pure value like so

def h(v: Int): Int = v + 1

then it is best to assume it is blocking. Here h is blocking in the sense of the thread that called it being blocked until v + 1 is computed.

Applying this principle to readLine

def readLine(): String

we see it is returning pure value String so we assume it is blocking. Analysing the source code we see the following stacktrace

java.io.Reader#read(char[], int, int)
java.io.BufferedReader#fill
java.io.BufferedReader#readLine(boolean)
java.io.BufferedReader#readLine()
scala.io.StdIn#readLine

where read states

Reads characters into a portion of an array. This method will block until some input is available, an I/O error occurs, or the end of the stream is reached.

Upvotes: 5

Related Questions