Easy approach to learn Threads

How to create a Thread?

Why Runnable is preferred over Thread?

  1. In OOPS, we extend the class to add new functionality, modify or improve functionality. If you are not making any modification on Thread functionality then we should go for Runnable Interface instead.
  2. Runnable represent a task. It can be executed by either plain Thread or Executor. With Runnable, we are separating the task from execution which is a flexible design.
  3. By extending the Thread, we have the overhead of inheriting all the Thread methods.

How to pause a thread?

How to interrupt a thread?

How to fetch the output from a Thread?

How do threads communicate?

How to protect shared data when it is accessed by multiple threads?

How to achieve thread safety?

  1. Minimize the sharing of objects between multiple threads.
  2. In case if the object is shared between multiple threads, multiple access should be restricted on the shared object. synchronize/Lock the shared object calls to ensure single access to the shared resource at any given point in time.
  3. Using immutable classes in multi-threaded environments is the best approach since the state of these instances cannot be changed.

Why Thread pool is better than a thread?

  1. Creation of thread is a costly process. Because it consumes time, CPU process (because OS has to create a separate process for the thread creation), and there is a limit on no. of threads created per JVM. So, creating a thread for a task is costlier than picking an already created thread from the thread pool.
  2. If we use a thread pool, we can reuse the fixed set of Threads(value of no. of threads is very much bounded) to do the tasks. Whereas in Threads, we have to create a thread for every incoming task which is unbounded.
  3. Thread pool uses threads which are already created. So, the task completion time is much quicker when compared to Thread.

How to create, manage Thread pools in Java?



Comments

Popular posts from this blog

Distributed database design using CAP theorem

SQL Analytical Functions - Partition by (to split resultset into groups)

Easy approach to work with files in Java - Java NIO(New input output)