good-story icon indicating copy to clipboard operation
good-story copied to clipboard

In platform Threads there "is no context switch"?

Open fjf2002 opened this issue 1 year ago • 1 comments

Hello Joao,

I've read your article at https://itnext.io/kotlin-coroutines-vs-java-virtual-threads-a-good-story-but-just-that-91038c7d21eb . I couldn't find out how to connect with you otherwise, so I'm trying it here.

In your article, you say,

In a concurrent environment with just the use of just of platform Threads, there is no context switch, and therefore making a blocking call always means waiting for the blocking call to finish before being allowed to continue. Coroutines or Continuations explore threads to the maximum by making sure that we avoid anything to block whenever that is possible.

Well, wrong. Or at least misleading. The thing is, in a multitasking operating system, we have

  • processes,
  • threads,
  • and now in both kotlin and java: coroutines (aka virtual threads aka fibers).

All of these execution models are being managed by some scheduler, and on blocking operations, control (i. e. the CPU) is given away to others.

The difference is, processes and threads are managed by the OS, whereas the coroutines discussed are managed by the Java/Kotlin compiler and/or runtime.

From a programmer's standpoint, one can partly abstract away who manages his multitasking. So at first glance, "inventing" coroutines in Java/Kotlin seems like re-inventing the wheel. The sole point is, in my judgement: coroutines are more lightweight than threads, just as threads are more lightweight than processes.

P. S.: There already happened a step in previous Java versions to make multithreading more lightweight: The introduction of thread pools, and the idea that so-called executors distribute runnables across the thread pool. This lowered thread construction/termination costs (as opposed to constructing one thread for each runnable).

P. P. S.: It is interesting to see that browsers kind of went the other way: browser tabs are running in separate processes, for better isolation (security, and perhaps stability).

fjf2002 avatar Mar 30 '23 19:03 fjf2002