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 😊


  1. Very good, This information is essential and informative which you have shared here. Read more info about Java Homework Help Online. It is beneficial for beginners to develop their knowledge. It is very gainful information. Thanks for share it.

  2. You are giving such interesting information. It is great and beneficial info for us, I really enjoyed reading it. Thankful to you for sharing an article like this.Java Assignment Help Online


Post a Comment

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

Threads in Java - CountDownLatch (Part 12)

A CountDownLatch is a synchronizer which allows one thread to wait for one or more threads before starts processing. A good application of  CountDownLatch is in Java server-side applications where a thread cannot start execution before all the required services are started. Working A  CountDownLatch is initialized with a given count which is the number of threads it should wait for. This count is decremented by calling countDown() method by the threads once they are finished execution. As soon as the count reaches to zero, the waiting task starts running. Code Example Let us say we require three services, LoginService, DatabaseService and CloudService to be started and ready before the application can start handling requests. Output Cloud Service is up! Login Service is up! Database Service is up! All services are up. Now the waiting thread can start execution. Here, we can see that the main thread is waiting for all the three services to start before starting its own

I/O in Java - Masterclass (Part 0)

IO in Java Java input and output processes the input and produces the output based on the input. Java uses streams to perform input and output operations. In this masterclass on I/O, we will learn about the nitty gritty details of the File IO/NIO with lots of code examples. You can follow the below trail to dive deep into Java I/O Part 1 - Basics Part 2 - IO vs. NIO Part 3 - try-with-resources Part 4 - Directory Operations Part 5 - File Operations Part 6 - Temporary File Operations 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  Facebook ,  Twitter  or  Linked In  or say Hi by  email . Happy Coding 😊