3

In order to have a deep understanding of Reactive Programming I was trying to reimplement, in a very simple way, the RxJava Observable class. This made me ask some important questions about reactive programming approach. I want to share them with you.

What I don't get is:

reactive programming makes use of callbacks, then the heavy and asynchronous operations are implemented by a worker thread (not the main thread) of our application. This worker thread waits for I/O operation, processing, etc. and when it finishes, then it calls back the caller through a callback method. The advantage can be that the main thread doesn't have to get blocked in order to wait for the response of a processing, because it's asynchronous and because it's called back when the process is finished.

My question is:

what is the advantage over simple multithreading? I mean, in multithreading there is no callback, so the worker thread doesn't call back the main thread, anyway it returns the result to the caller (using a Callable for example).

Both these two scenarios have one worker thread getting blocked in order to wait for I/O operations or processing.

The only difference is a callback over a return.

So what am I missing?

Alessandro Argentieri
  • 2,901
  • 3
  • 32
  • 62

1 Answers1

2

"reactive programming makes use of callbacks"

not exactly. It is asynchronous programming which makes use of callbacks, and reactive programming is a special case of asynchronous programming. Actually, your question concerns asynchronous programming in general and does not deal with reactive programming peculiarities.

When a thread is running, it alternates between active and blocking states. In both states, the thread occupies large amount of memory for its call stack. Asynchronous procedure is supposed to employ a thread (and stack) only in active state and not to block any thread in its blocked state. This is the only difference and the main advantage of asynchronous programming.

But, one cannot prevent an asynchronous procedure from making a blocking operation, e.g. blocking I/O or Semaphore.aquire(). In such a case asynchronous programming become multithreading programming and loose its advantages.

The art of asynchronous programming is to avoid blocking operations whenever possible. If, nevertheless, a program performs blocking operations, the problem is not in asynchronous programming, but in programmer's qualification or in poor environment, e.g. absence of asynchronous JDBC drivers.

Alexei Kaigorodov
  • 13,189
  • 1
  • 21
  • 38
  • In terms of thread states, does "blocked" thread has a RUNNABLE state? See https://stackoverflow.com/questions/48968984/java-threads-state-when-performing-i-o-operations (And "active" thread has a RUNNING state?) – Ekaterina Jul 07 '22 at 21:04