Search code examples
javaasynchronousreactive-programming

Asynchronous Programming and Reactive Programming


This question is in my mind about a year. Actually are there any differences in Asysnchronus and Non-blocking. When we call the blocking part in our code then it becomes blocking which is synchronous and at the same time it will not be non-blocking.

If we are creating another thread apart from main thread to make asynchronous programming and we have to return some value so we have to define join() method in java and join() is blocking operation then is it actually asynchronous?

I need to know answer for the following questions

  1. If blocking is similar to synchronous then what is the different between asynchronous and non blocking. Should it be similar ? if not then why?

  2. Reactive Programming which is non blocking does it fully asynchronous programming?


Solution

  • Consider two parallel algorithms, producer and consumer. If the consumer works faster than the producer, we have to block the consumer algorithm until the producer provides new data. Generally, we have two ways to block the consumer:

    1. Implement the consumer as a thread and block that thread.
    2. Implement the consumer as a task running on a thread pool and return from that task (and tell the producer to restart the task when the data is ready). The first method of implementing the consumer is synchronous, and the second is asynchronous.

    Now consider the opposite case: the producer is faster than the consumer. Then again, we have two options to block the producer:

    1. Implement the producer as a thread and block that thread.
    2. Implement the producer as a task running on a thread pool and return from that task (and tell the consumer to restart the producer task when it is able to receive data). Naturally, the first option is synchronous and the second is asynchronous. And the second, asynchronous option to define the interaction between a fast producer and a slow consumer is called reactive programming.

    So, reactive programming is a subset of asynchronous programming. There are many different protocols to define the interaction between asynchronous activities, and reactive programming is only one of them, which cannot cover all possible cases of asynchronous communication.

    I tried to collect asynchronous protocols in this module: https://github.com/akaigoro/df4j/tree/API-8/df4j-protocols. Other protocols can be (re)invented, for example, byte streams with or without backpressure, analogous to synchronous InputStream and OutputStream. I am sure any synchronous protocol has its asynchronous counterpart.