Skip to main content

Threads in Java - Masterclass (Part 0)

Threads in Java
Multithreading is a way to introduce concurrency in a program. In any case, if there are parallel paths in our program (parts which do not depend on the result from another part), we can make use of multithreading.
One should exploit this feature, especially with all these multiple core machines nowadays.

Below are a few reasons why we should use multithreading -

1. Keep a process responsive

There was once a time when you would print a document in MS Word and the application would freeze for an annoyingly long amount of time until the job finished. Eventually, Microsoft solved this problem by running a printing job parallel to the main thread/ GUI thread. 
To be clear though, not only GUI apps but Network services have to keep an ear to the ground for new clients, dropped connections and cancellation requests. In either case, it is critical to do the heavy lifting on a secondary thread to keep the user satisfied.

2. Keep a processor busy

Keeping a processor busy can be a tough task even for the top programmers. There are all kinds of reasons that make a processor stall. The most prevalent and mundane is common disk and network I/O. When a single-threaded application accesses a file, calls a web service, or streams from your webcam, processor sits idly and kills time. 
Occasionally, there isn't much to do but to wait for the I/O to complete. For example, let's say you have a date on Valentine's day 💖 and you call up a restaurant for bookings. While you are waiting for your confirmation, you can do another task such as ordering flowers 🎕. That way you are utilizing your time instead of sitting idle. 
Similarly, we can design our application in a way so that we can keep our processor busy and get maximum utilization of it. Try to think ahead.

3. Keep multiple processors busy

Let's say you have a single threaded application that has a monomaniacal focus on computation. It uses the minimum I/O, effective use of caching, and has predictable loops that your compiler can turn into a data-parallel operation. You are golden.

Unless you have more than one processor. 

Today's hardware is not getting more Hertz, it is getting more pipelines, more cores and additional processors. This means if we max out one process calculating a billion digits of 𝜫, the other processors wondering what the fuss is all about.

If we run multiple processors, that is. multiple distinct applications or multiple instances of a single application, the OS will come to rescue and goad those other processors into action. But if we want our application to utilize the maximum amount of hardware it is on, we need to give OS scheduler multiple things to work on simultaneously. And we can achieve this via multiple threads.

4. Simplify the coding of cooperating tasks

Just as many programming problems both have iterative and recursive implementations, many programming problems also have both serial and concurrent variations. The version we choose depends on the nature of the specific problem.

For instance, the recursive version of Quicksort makes a whole lot more sense than the iterative version. Similarly, trying to write a multi-client network service with just one thread, though possible, isn't fun, isn't natural. When we refactor it into multiple threads, the code becomes logically simpler. One thread per client, one thread to rule them all.

The key in using threads to simplify code is to try to keep our functions and methods on one train thought. Rather than turn our code into an arthritic mess trying to interleave multiple simultaneous tasks, code each task separately. Code each line block with one mind. Let the OS thread scheduler do the interleaving.

As you can see since there are various use cases of multithreading in programming, it is one of the most important concepts and it almost always beneficial to master this concept. Keeping this thing in mind, I have created a series of blog posts discussing various concepts of Multithreading in Java.

This blog post lists all the topics that are covered in the threads' masterclass.

All of these posts include code examples to understand the concept. You can find the code of these examples on my GitHub repository. Feel free to fork or open issues, if any.

I would love to hear your thoughts on this and would like have suggestions from you to make it better. 

Feel free to befriend me on FacebookTwitter or Linked In or say Hi by email.

Happy Coding 😊

Comments

Popular posts from this blog

Parsing XML using Retrofit

Developing our own type-safe HTTP library to interface with a REST API can be a real pain as we have to handle many aspects -
making connectionscachingretrying failed requeststhreadingresponse parsingerror handling, and more.  Retrofit, on the other hand, is a well-planned, documented and tested library that will save you a lot of precious time and headaches. In this tutorial, we are going to discuss how we can parse the XML response returned from https://timesofindia.indiatimes.com/rssfeedstopstories.cms using the Retrofit library.

To work with Retrofit, we need three classes -  Model class to map the JSON dataInterfaces which defines the possible HTTP operationsRetrofit.Builder class - Instance which uses the interface and the Builder API which allows defining the URL endpoint for the HTTP operation. Every method of the above interface represents on possible API call. The request type is specified by using appropriate annotations (GET, POST). The response is returned as a Call object…

Threads in Java - Basics (Part 1)

Hello everyone, today we are going to discuss one of the most important concepts in Java - Multithreading.
In the first part of this multi-part blog series, we will be discussing the basics of threads, how can we create them? which is the best approach? and many other questions like these. So without further ado, let's get started.
What are threads? Let's say you are Batman (pretty cool, eh? 😊) and your arch-enemy, the master alchemist Ra's al Ghul has brewed a dangerous potion from the Lazarus Pit. To avenge his earlier defeats by the hands of The Dark Knight, he has spread the potions all over the Gotham city.  Now, the only way to save citizens of Gotham is to find the cure of the potion (hidden in the city somewhere) and find Ra's as well before he can devise a new plan to destroy the city.  Batman calls Nightwing (the original Robin) and asks his help in finding Ra's. Batman decides to find the cure of the deadly potion. In the end, both Batman and Robin wer…