Saturday, May 22, 2021

Multithreading: Key Concepts

  • Daemon Thread
    • If a daemon thread creates a new thread; new thread will be by default daemon
    • Daemon thread is low priority thread which runs in background 
    • It provides support & services to running non-daemon threads
    • For example, GC or finalizer, etc.
    • Once all user threads are terminated, JVM will terminate the program by terminating any running daemon threads
  • Thread Priorities
    • New thread created will by default have priority of creating thread
    • Priority is represented by a number between 1 to 10
    • 1 = MIN_PRIORITY, 5 = NORM_PRIORITY and 10 = HIGH_PRIORITY
  • Thread Interruption
    • If any thread is in sleeping or waiting state, calling interrupt() method on thread, breaks the thread state and throws InterruptedException
    • If the thread is not in waiting state, method will not throw exception but will set interrupted flag to true
  • ThreadLocal
    • All threads of an Object share it’s variables, so the variables are not thread safe
    • We can achieve thread safety by synchronization, but if we want to avoid synchronization, we can use ThreadLocal
    • Every thread has its own ThreadLocal which they can use to set() & get() for the values of static private variables local to the Thread
  • Thread Dump
    • Is useful for analyzing bottlenecks and deadlock situations in application
    • There are different ways to generate ThreadDump
      • VisualVM Profiler
      • Jstack: jstack pid >> file.tdump
      • Kill - PID: on console output i.e. System.out
      • jcmd: java 8 & above
  • ThreadMXBean
    • It is an interface which helps in detecting deadlocks
    • Thread.getThreadMXBean().findMonitorDeadlockedThreads()
  • Avoid Deadlocks
    • Avoid nested locks
    • Lock only what is required: field => block => method => object
    • Avoid waiting indefinitely
    • Follow Lock Orders: Thread2 should acquire locks in same order as Thread1
    • Use join() method: sequential execution of threads

No comments:

SpringBoot: Features: SpringApplication

Below are a few SpringBoot features corresponding to SpringApplication StartUp Logging ·          To add additional logging during startup...