Java Multi-threading Summary 2021

Nuwan Zen
5 min readFeb 12, 2021
Photo by aisvri on Unsplash

Thread

Thread Is a sub-process that follows a separate execution path, different stack frame and executes independently but they share the same process resources. Multi-threading is the process of executing one or more threads simultaneously that helps in executing multiple tasks at the same time.

Advantages

  • less memory
  • fast
  • efficient
  • Supports multitasking
  • Exception in one thread does not affect the other

Thread lifecycle

  • New
  • Runnable
  • Running
  • Non-Runnable
  • Terminated

Ways to create a thread?

  • Extending Thread class
  • Implementing Runnable class

Thread.start() vs Thread.run()

Class java.lang.Thread.start() Creates a new thread and the run() method is executed on the newly created thread. Can’t be invoked more than one time otherwise throws java.lang.IllegalStateException.

Interface java.lang.Runnable.run(), No new thread is created and the run() method is executed on the calling thread itself. Multiple invocation is possible

Constructors of a thread class

  • Thread()
  • Thread(String name)
  • Thread(Runnable r)
  • Thread(Runnable r, String name)

Methods of a thread used for communicating with each other?

  • wait() method
  • notify() method
  • notifyAll() method

User thread vs a daemon thread?

user threads — High priority, Runs in foreground, Performs specific complex task, JVM always waits for active user thread to complete before shutdown, Created by the Java application for executing some task, It is independent.

Daemon threads — Low priority thread, Runs in background, Performs supporting task, JVM does not wait for daemon thread to complete before shutdown, Created by the JVM, depends on the user threads

We can create a daemon thread using the setDaemon(true) method of the Thread class. We need to use this method before calling the start() method else it will throw IllegalThreadStateException.

Pause a thread

Using sleep() with a time to sleep, once it awakes state will be changed to runnable and starts execution.

Methods

wait() is part of the Object class and is used to release the lock

sleep() is part of the Thread class and does not release any lock.

join() method waits for the currently executing task to stop execution

notify() unblocks a single waiting thread

notifyAll() unlocks all the waiting threads.

Thread priority

1 is the lowest and 10 is the highest. but also depends on the Thread Scheduler implementation.

Thread scheduler and time slicing?

Thread scheduler is a service that belongs to the operating system that schedules or allocates CPU time for thread execution.

Time slicing is the process of diving the available CPU time for the runnable threads.

Context switching in multithreading

Storing and restore the CPU state of a thread. helps in continuing the thread execution from the same point where it was paused.

When to use synchronized method or block

wait(), notify(), and notifyAll() methods have a dependency on the Object monitor because if a thread is in a wait state, then it leaves the Object monitor and returns until it calls the notify() method. Since all these methods require synchronization with each other, we need to call them only from the synchronized method or block.

How to achieve thread-safety

  • Synchronization
  • Atomic concurrent class
  • Concurrent Lock interface
  • volatile keyword — reads the value of the variable directly from the memory instead of cache.
  • immutable classes
  • Thread-safe classes

Thread Dump

Group of active threads that are used to analyze bottlenecks and deadlock situations.can create using profiler, kill-3 command, jstack tool.

Deadlock

Is a situation in which threads are blocked forever. This occurs when threads access the same resource. BLOCKED state threads in thread dumps are deadlocks. can avoid by avoiding the usage of nested locks, waiting infinitely, and locking only what is required.

Inter-thread communication

Is the process of communication between the synchronized threads and is used to avoid thread polling. This is useful when one thread pauses its execution in the critical state and allows another thread to enter the execution in the same critical state.

Process and a thread

  • A process is a program in execution, Thread is a subset of a process
  • Processes maintains different address space, Threads maintains same address same
  • Context switching is slower in Processes and faster Threads
  • Inter-process communication is slower in Processes and faster in Threads
  • Any change in parent process does not affect the child process but Any change in parent thread will affect the child thread

Shutdown hook

Is a thread that is implicitly called by the JVM to clean up the resources before JVM shutdown either normally or abruptly.

Interrupting a thread

To wakeup a thread from sleep or wait state. by calling interrupt() that throws InterruptedExeception.

Synchronization

Is the process of controlling the access of multiple threads to the shared resource. when a thread uses the shared resource, it locks it so that the other thread cannot use it until it releases the lock. This avoids some errors. Implemented using,

  • By synchronization method
  • Synchronization block
  • static synchronization

Synchronous and asynchronous

In asynchronous programming, multiple threads can perform the same task. In synchronous programming, when a thread starts working on a task, it is available for other tasks only once the assigned task is completed.

Race condition

Is a situation where multiple threads access shared resources same time and going to error situation.

Thread pool

A thread pool represents a group of threads that are waiting for a task. The service provider pulls one thread at a time and assigns a task to it.

Components of the Concurrency API

  • Executor — Executor interface is used to execute a particular task
  • ExecutorService — A subinterface of the Executor interface which has special functions to manage the life cycle.
  • ScheduledExecutorService
  • Future
  • TimeUnit
  • ThreadFactory
  • Locks — lock interface contains the lock() and unlock() method and guarantees the order in which the threads are waiting for execution. similar to a synchronized block. supports timeout operations.
  • DelayQueue
  • BlockingQueue — it supports waiting for available space before inserting
  • Semaphore
  • Phaser
  • CyclicBarrier
  • CountDownLatch
  • FarkJoinPool

Callable vs Runnable interface

  • Both interfaces are used to execute multiple tasks.
  • Callable Returns a value Runnable Does not
  • Callable throws CheckedException Runnable does not
  • Callable after Java 5, Runnable before

Atomic action in Concurrency

Atomic action performs a single task without any interference of other methods. It is part of the Concurrent package. Once the atomic action starts, we cannot stop or pause it in between. All areas and write operations of primitive variables and volatile variables are atomic operations.

How can we make sure of the order of the threads

Using the join() method.

Read my other blogs:

--

--

Nuwan Zen

Sometimes A software Engineer, sometimes a support engineer, sometimes a devops engineer, sometimes a cloud engineer :D That’s how the this life goes!