Reactive Programming in Java: How, Why, and Is It Worth Doing? History of Multithreading

Reactive Programming in Java: How, Why, and Is It Worth Doing? History of Multithreading

History of Multithreading

How does multithreading work in Java? The good old multithreading in Java uses basic multithreading primitives:

  • Threads
  • Synchronization
  • Wait/notify

Difficult to write, difficult to debug, difficult to test.

Java 5

  • Future interface:
  • V get()
  • boolean cancel()
  • boolean isCancelled()
  • boolean isDone()
  • Executors
  • Callable interface
  • BlockingQueue

Reactive Programming in Java How Why and Is It Worth Doing History of Multithreading.jpg


The Future interface appeared in Version 5. Future is a kind of promise, something we can get from a function, the result of some uncompleted asynchronous operation.

Then a method ‘get’ appeared in the Future interface. It blocks a call until the completion of the calculation. For example, we have Future which returns data from the DB, and we address the get method:

Future getDBData();

getDBData().get();

Here blocking occurs. In fact, there is no advantage of using Future here. When can we get an advantage? For example, we set a task, execute it, address the get method, and use blocking at this point:

Future f = getDBData();

doOutJob();

f.get();

Returning to the metaphor of manager and employees, we set a task, did some job, and then waited for the task to be completed. And what if we need to pass the result of this job to another person? We have already reviewed such a case: do the job, pass the results, and then get back. In the case of parallelism, there is no such possibility.

The Future capabilities are very limited. For instance, we can find out if this task was executed:

Future f = getDBData();

doOutJob();

if (!f.isDone) doOtherJob();

 

f.get();

If the task is not completed yet, we can do something else. Anyway, we’ll miss this point: either the task is not completed, or it is, but we are busy with other things. Points of synchronization are not very clear here.

The Future interface had minimal capabilities in Java 5 and was not easy to use.

Which are the business tasks to be performed by a typical application?

 

Interested in learning how to program with Java or in upgrading your Java programming skills?

Check out our trainings