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 😊


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 connections caching retrying failed requests threading response parsing error 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  using the Retrofit library. To work with Retrofit, we need three classes -  Model class to map the JSON data Interfaces which defines the possible HTTP operations Retrofit.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 respon

Material design profile page in Android

Hey everyone, some days back I was working on one my personal Android project. In that project, I was supposed to create a simple profile page for a user. This profile page was supposed to show some basic details of a user. The output of this UI will be like this - Profile page screen I created the profile page using material design and in this post, I am going to discuss a step by step tutorial to create a simple yet elegant profile page. Without further ado, let's get started. Creating a new project Click on File ➤ New Project ➤ Empty Activity and fill the necessary details. Change styles.xml file Navigate to app\src\main\res\values\styles.xml Change the style value from DarkActionBar to NoActionBar as below <resources> <!-- Base application theme. --> <style name= "AppTheme" parent= "Theme.AppCompat.Light.NoActionBar" > <!-- Customize your theme here. --> <item name= "colorPr