Multithreading in Java

Multithreading in Java is a very important topic. I have written a lot about Threads in Java. Java Thread is a lightweight process that executes some task. Java provides multithreading support with the Thread class and an application can create multiple threads executing concurrently.

A thread is a lightweight sub-process, the smallest unit of processing. Multiprocessing and multithreading, both are used to achieve multitasking.

However, we use multithreading than multiprocessing because threads use a shared memory area. They don't allocate separate memory area so saves memory, and context-switching between the threads takes less time than process.

There are two types of threads in an application – user thread and daemon thread. When we start an application, main is the first user thread created and we can create multiple user threads as well as daemon threads. When all the user threads are executed, JVM terminates the program.

We can set different priorities to different Threads but it doesn’t guarantee that higher priority thread will execute first than lower priority thread. Thread scheduler is the part of Operating System implementation and when a Thread is started, it’s execution is controlled by Thread Scheduler and JVM doesn’t have any control on it’s execution.

We can create Threads by either implementing Runnable interface or by extending Thread Class.

Above is a one liner statement to create new Thread, Here we are creating Runnable as Anonymous Class, read this post to learn about inner class, nested class and anonymous inner class.

In last few weeks, I have posted some useful articles on multithreading in java, you can follow them in order to learn about Threads in Java.

Threads in Java

With Java 8 lambda expressions, we can create Thread in java like below too because Runnable is a functional interface.

1.Java Thread Example

This is the first post in the multithreading in java tutorial series. Read this to learn about Process and Thread. What is the difference between Thread and Process. Benefits of using Threads and how we can create Threads using Runnable interface and Thread class. This post also compares Runnable interface with Thread class.

2.Java Thread Sleep

Java Thread sleep is used to pause the execution of current thread. We will use Thread sleep extensively in future posts, so it’s good to know how it works and is it accurate or not?

3.Java Thread Join

Sometimes we need to wait for other threads to finish it’s execution before we can proceed. We can achieve this using Thread join, learn how it works and when we should use it.

4.Java Thread States

Understanding different states of thread is important. Learn how thread changes it’s state and how thread scheduler changes thread state.

5.Java Thread wait, notify and notifyAll

Java Object class contains three methods using which threads can communicate about the lock status of a resource. Learn with example usage of these Object class methods in a simple Wait-Notify implementation.

6.Java Thread Safety and Java Synchronization

We know that Threads share Object resources, it can lead to data corruption because these operations are not atomic. Learn how we can achieve thread safety in java using different methods. Read this post to learn about the correct usage of synchronization, synchronized methods and synchronized blocks.

There are various examples of synchronized usage and the post explains what are the issues with them.

7.Java Exception in thread main

JVM creates first thread using main method. This post explains about some common exceptions we see in daily life and what is the root cause of them and how to fix them.

8.Thread Safety in Singleton Class

In this article, you will learn basic concepts of creating Singleton class. What are thread safety issues with different implementation. How we can achieve thread safety in Singleton class.

9.Daemon Thread in Java

A simple article explaining about daemon threads and how we can create daemon threads in java.

10.Java Thread Local

We know that threads share Object’s variables but what if we want to have thread-local variables created at class level. Java provides ThreadLocal utility class to create thread-local variables. Read more to learn about how we can create ThreadLocal variables in java program.

11.Java Thread Dump

Java Thread dump provides the current threads information for the program. Java Thread dump provides useful information to analyze performance issues with the application. You can use thread dump to find and fix deadlock situations. This post explains different methods that can be used to generate thread dump in java.

12.How to Analyze Deadlock and avoid it in Java

Deadlock is a situation where multiple threads are waiting for each other to release resources causing cyclic dependency. This article discusses about the situation in which we can get deadlock in a java program. How we can use Thread dump to find the deadlock and best practices to avoid deadlock in java program.

13.Java Timer Thread

This post explains how we can use Java Timer and TimerTask classes to create jobs to run at scheduled interval, an example program showing it’s usage and how we can cancel the timer.

14.Java Producer Consumer Problem

Before Java 5, producer-consumer problem can be solved using wait() and notify() methods but introduction of BlockingQueue has made it very easy. Learn how we can use BlockingQueue to solve producer consumer problem in java.

15.Java Thread Pool

Java Thread Pool is a collection of worker threads waiting to process jobs. Java 5 introduction of Executor framework has made it very easy to create thread pool in java using Executors and ThreadPoolExecutor classes. Learn how to use them to create thread pool in java.

16.Java Callable Future

Sometimes we wish Thread could return values that we can use. Java 5 Callable can be used in that case that is similar as Runnable interface. We can use Executor framework to execute Callable tasks.

17.Java FutureTask Example

FutureTask class is the base concrete class that implements Future interface. We use it with Callable implementation and Executors for asynchronous processing. FutureTask provide implementation methods to check the state of the task and return the value to the calling program once it’s processing is finished. It comes handy when you want to override some of the implementation methods of the Future interface.

Advantages of Java Multithreading
  1. It doesn't block the user because threads are independent and you can perform multiple operations at the same time.

  2. You can perform many operations together, so it saves time.

  3. Threads are independent, so it doesn't affect other threads if an exception occurs in a single thread.

Multitasking

Multitasking is a process of executing multiple tasks simultaneously. We use multitasking to utilize the CPU. Multitasking can be achieved in two ways:

  • Process-based Multitasking (Multiprocessing)

  • Thread-based Multitasking (Multithreading)

1.Process-based Multitasking (Multiprocessing)
  • Each process has an address in memory. In other words, each process allocates a separate memory area.

  • A process is heavyweight.

  • Cost of communication between the process is high.

  • Switching from one process to another requires some time for saving and loading registers, memory maps, updating lists, etc.

2 Thread-based Multitasking (Multithreading)
  • Threads share the same address space.

  • A thread is lightweight.

  • Cost of communication between the thread is low.

Note: At least one process is required for each thread.
What is Thread in java

A thread is a lightweight subprocess, the smallest unit of processing. It is a separate path of execution.

Threads are independent. If there occurs exception in one thread, it doesn't affect other threads. It uses a shared memory area.

Java Multithreading

As shown in the above figure, a thread is executed inside the process. There is context-switching between the threads. There can be multiple processes inside the OS, and one process can have multiple threads.

Java Thread class

Java provides Thread class to achieve thread programming. Thread class provides constructors and methods to create and perform operations on a thread. Thread class extends Object class and implements Runnable interface.

Java Thread Methods
S.N. Modifier and Type Method Description
1) void start() It is used to start the execution of the thread.
2) void run() It is used to do an action for a thread.
3) static void sleep() It sleeps a thread for the specified amount of time.
4) static Thread currentThread() It returns a reference to the currently executing thread object.
5) void join() It waits for a thread to die.
6) int getPriority() It returns the priority of the thread.
7) void setPriority() It changes the priority of the thread.
8) String getName() It returns the name of the thread.
9) void setName() It changes the name of the thread.
10) long getId() It returns the id of the thread.
11) boolean isAlive() It tests if the thread is alive.
12) static void yield() It causes the currently executing thread object to pause and allow other threads to execute temporarily.
13) void suspend() It is used to suspend the thread.
14) void resume() It is used to resume the suspended thread.
15) void stop() It is used to stop the thread.
16) void destroy() It is used to destroy the thread group and all of its subgroups.
17) boolean isDaemon() It tests if the thread is a daemon thread.
18) void setDaemon() It marks the thread as daemon or user thread.
19) void interrupt() It interrupts the thread.
20) boolean isinterrupted() It tests whether the thread has been interrupted.
21) static boolean interrupted() It tests whether the current thread has been interrupted.
22) static int activeCount() It returns the number of active threads in the current thread's thread group.
23) void checkAccess() It determines if the currently running thread has permission to modify the thread.
24) static boolean holdLock() It returns true if and only if the current thread holds the monitor lock on the specified object.
25) static void dumpStack() It is used to print a stack trace of the current thread to the standard error stream.
26) StackTraceElement[] getStackTrace() It returns an array of stack trace elements representing the stack dump of the thread.
27) static int enumerate() It is used to copy every active thread's thread group and its subgroup into the specified array.
28) Thread.State getState() It is used to return the state of the thread.
29) ThreadGroup getThreadGroup() It is used to return the thread group to which this thread belongs
30) String toString() It is used to return a string representation of this thread, including the thread's name, priority, and thread group.
31) void notify() It is used to give the notification for only one thread which is waiting for a particular object.
32) void notifyAll() It is used to give the notification to all waiting threads of a particular object.
33) void setContextClassLoader() It sets the context ClassLoader for the Thread.
34) ClassLoader getContextClassLoader() It returns the context ClassLoader for the thread.
35) static Thread.UncaughtExceptionHandler getDefaultUncaughtExceptionHandler() It returns the default handler invoked when a thread abruptly terminates due to an uncaught exception.
36) static void setDefaultUncaughtExceptionHandler() It sets the default handler invoked when a thread abruptly terminates due to an uncaught exception.



Instagram