Skip to main content

Java Multithreading 2021

Thread

Thread Is a subprocess that follows a separate execution path, different stack frame and executes independently but they share the same process resources. 

Multithreading 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.

Comments

Popular posts from this blog

Oracle Database 12c installation on Ubuntu 16.04

This article describes how to install Oracle 12c 64bit database on Ubuntu 16.04 64bit. Download software  Download the Oracle software from OTN or MOS or get a downloaded zip file. OTN: Oracle Database 12c Release 1 (12.1.0.2) Software (64-bit). edelivery: Oracle Database 12c Release 1 (12.1.0.2) Software (64-bit)   Unpacking  You should have following two files downloaded now. linuxamd64_12102_database_1of2.zip linuxamd64_12102_database_2of2.zip Unzip and copy them to \tmp\databases NOTE: you might have to merge two unzipped folders to create a single folder. Create new groups and users Open a terminal and execute following commands. you might need root permission. groupadd -g 502 oinstall groupadd -g 503 dba groupadd -g 504 oper groupadd -g 505 asmadmin Now create the oracle user useradd -u 502 -g oinstall -G dba,asmadmin,oper -s /bin/bash -m oracle You will prompt to set to password. set a momorable password and write it down. (mine is orac

DBCA : No Protocol specified

when trying to execute dbca from linux terminal got this error message. now execute the command xhost, you probably receiving No protocol specified xhost:  unable to open display ":0" issue is your user is not allowed to access the x server. You can use xhost to limit access for X server for security reasons. probably you are logged in as oracle user. switch back to default user and execute xhost again. you should see something like SI:localuser:nuwan solution is adding the oracle to access control list xhost +SI:localuser:oracle now go back to oracle user and try dbca it should be working

Java Head Dump Vs Thread Dump

JVM head dump is a snapshot of a JVM heap memory in a given time. So its simply a heap representation of JVM. That is the state of the objects. JVM thread dump is a snapshot of a JVM threads at a given time. So thats what were threads doing at any given time. This is the state of threads. This helps understanding such as locked threads, hanged threads and running threads. Head dump has more information of java class level information than a thread dump. For example Head dump is good to analyse JVM heap memory issues and OutOfMemoryError errors. JVM head dump is generated automatically when there is something like OutOfMemoryError has taken place.  Heap dump can be created manually by killing the process using kill -3 . Generating a heap dump is a intensive computing task, which will probably hang your jvm. so itsn't a methond to use offetenly. Heap can be analysed using tools such as eclipse memory analyser. Core dump is a os level memory usage of objects. It has more informaiton t