08 January 2021

#Multithread

MultiThread
What is the difference between Process and Thread?
What are the benefits of multi-threaded programming?
What is difference between user Thread and daemon Thread?
What are different states in lifecycle of Thread?
What do you understand about Thread Priority?
What is Thread Scheduler and Time Slicing?
What is context-switching in multi-threading?
What is volatile keyword in Java
What is ThreadLocal?
What is Thread Group? Why it’s advised not to use it?
What is Java Thread Dump, How can we get Java Thread dump of a Program?
What is Deadlock? How to analyze and avoid deadlock situation?
What is Java Timer Class? How to schedule a task to run after specific interval?
What is Thread Pool? How can we create Thread Pool in Java?
What will happen if we don’t override Thread class run() method?
What is atomic operation? What are atomic classes in Java Concurrency API?
What is Lock interface in Java Concurrency API? What are it’s benefits over synchronization?
What is Executors Framework?
What is BlockingQueue? How can we implement Producer-Consumer problem using Blocking Queue?
What is Callable and Future?
What is FutureTask class?
What are Concurrent Collection Classes?
What is Executors Class?
What are some of the improvements in Concurrency API in Java 8?
Why thread communication methods wait(), notify() and notifyAll() are in Object class?
Why wait(), notify() and notifyAll() methods have to be called from synchronized method or block?
Why Thread sleep() and yield() methods are static?
Which is more preferred – Synchronized method or Synchronized block?
How can we create a Thread in Java?
How can we pause the execution of a Thread for specific time?
How can we make sure main() is the last thread to finish in Java Program?
How does thread communicate with each other?
How can we achieve thread safety in Java?
How to create daemon thread in Java?
Can we call run() method of a Thread class?

Multitasking - It is a process of executing multiple tasks simultaneously. We use multitasking to utilize the CPU. 

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.
Thread-based Multitasking (Multithreading)

  • Threads share the same address space.
  • A thread is lightweight.
  • Cost of communication between the thread is low. is a process of executing multiple tasks simultaneously. We use multitasking to utilize the CPU. 

Multithreading

  • Life Cycle - New, Runnable, Running, Waiting, Blocked, Dead
  • Start Method - This method can’t be invoked twice it will throw illegal state of the thread exception
  • Two ways to create a Thread - By extending Thread class, By implementing Runnable interface.
  • Multi thread shares the heap memory. Servlet performs better because its support multi threading.
  • Thread created in the application by the user is called user thread.
  • Thread will start with zero that is t-0..t-1..t-2 etc
  • Thread.currentThread.getName used to get the current thread name.
  • A class implements Runnable and override the run method with our own code
  • We can specify the priority of thread but it doesn’t guarantee that higher priority thread will get executed before lower priority thread. Thread priority is an int whose value varies from 1 to 10 where 1 is the lowest priority thread and 10 is the highest priority thread.
  • Time Slicing is the process to divide the available CPU time to the available runnable threads. Allocation of CPU time to threads can be based on thread priority or the thread waiting for longer time will get more priority in getting CPU time. Thread scheduling can’t be controlled by java, so it’s always better to control it from application itself.
  • Communication between threads will happen with the help of wait , notify and noftifyAll method. To know the locked status of the resource that has been shared.
  • Thread sleep() and yield() methods work on the currently executing thread. So there is no point in invoking these methods on some other threads that are in wait state. That’s why these methods are made static so that when this method is called statically, it works on the current executing thread and avoid confusion to the programmers who might think that they can invoke these methods on some non-running threads.
  • When we use volatile keyword with a variable, all the threads read it’s value directly from the memory and don’t cache it. This makes sure that the value read is the same as in the memory.
  • Synchronized block is more preferred way because it doesn’t lock the object gets locked even though they are not related, it will stop them from execution and put them in wait state.
  • Thread class setDaemon(true) can be used to create daemon thread in java. We need to call this method before calling start() method else it will throw IllegalThreadStateException.
  • Thread thread = new Thread (new Task) -here the class Task has been passed to invoke the thread in it

  • One single thread is equal to one os thread. Creating a thread is costly and creating a thousands of thread is expensive. For that thread pool can be created to have fixed number of threads. Internally uses blocking queue in thread pool and it becomes thread safe.
  • If the task is CPU intensive then the ideal pool size is CPU core count If the task is IO instensive( that is io operations) then the ideal pool size will be high( count of number of task)
  • public void run() which is the method of runnable interface returns nothing
  • In case we need to return anything manually we can use callable interface.
  • If we are using callable interface service.execute will throw compile time exception Instead need to used service.submit for the task.
  • The main purpose of multithreading is to provide simultaneous execution of two or more parts of a program to maximum utilize the CPU time. 
  • A multithreaded program contains two or more parts that can run concurrently. Each part of such a program called a thread. 
  • Each thread has a separate path of its execution. So this way a single program can perform two or more tasks simultaneously.
  • Threads are lightweight processes; they share the same address space.
  • There is several thread states, a thread can be in any one of the state at a particular point of time. It can be running state. It can be ready to run state as soon as it gets CPU time. 
  • A running thread can be suspended. A suspended thread can be resumed. A thread can be blocked when waiting for a resource. At any time a thread can be terminated.
  • The Thread class and Runnable Interface
  • A thread can be created in two ways: 1)By extending Thread class 2) By implementing Runnable interface.
  • Before we learn how to create the thread. Lets have a look at the methods that helps in managing the threads.
  • we can not start a thread twice. After starting a thread, it can never be started again. If you does so, an IllegalThreadStateException is thrown. In such case, thread will run once but for second time, it will throw exception.

        • getName(): It is used for Obtaining a thread’s name
        • getPriority(): Obtain a thread’s priority
        • isAlive(): Determine if a thread is still running
        • join(): Wait for a thread to terminate or die
        • run(): Entry point for the thread
        • sleep(): suspend a thread for a period of time
        • start(): start a thread by calling its run() method
    What if we call run() method directly instead start() method?

    • Thread.Start() will start the thread. Run () method the thread will be considered as normal method. 
    • Each thread starts in a separate call stack. 
    • Invoking the run() method from main thread, the run() method goes onto the current call stack rather than at the beginning of a new call stack.
    Run method

    • We can call run() method of a Thread class but then it will behave like a normal method. 
    • To actually execute it in a Thread, we need to start it using Thread.start() method.

      Thread Scheduler

      • It is the Operating System service that allocates the CPU time to the available runnable threads. Once we create and start a thread, it’s execution depends on the implementation of Thread Scheduler.
      • Thread scheduler in java is the part of the JVM that decides which thread should run.
      • There is no guarantee that which runnable thread will be chosen to run by the thread scheduler.
      • Only one thread at a time can run in a single process.
      • It is the Operating System service that allocates the CPU time to the available runnable threads.
      • Once we create and start a thread, its execution depends on the implementation of Thread Scheduler.

      Thread Sleeping

      • Thread class sleep() method to pause the execution of Thread for certain time. Note that this will not stop the processing of thread for specific time, once the thread awake from sleep, it’s state gets changed to runnable and based on thread scheduling,it gets executed.
      • We can use Thread class sleep() method to pause the execution of Thread for certain time. 
      • Note that this will not stop the processing of thread for specific time, once the thread awake from sleep, it’s state gets changed to runnable and based on thread scheduling, and it gets executed.

      Thread Join

      • It make sure all the threads created by the program is dead before finishing the main function. 
      • The join() method waits for a thread to die. In other words, it causes the currently running threads to stop executing until the thread it joins with completes its task.
        • public void join()throws InterruptedException
        • public void join(long milliseconds)throws InterruptedException
      ThreadPoolExecutor constructor. Parameters of the constructor: 

      • corePoolSize - minimum pool size
      • maxpoolsize - maximum pool size,
      • keepAlive - time to keep the idle thread alive, 0 second for fixed and single thread pool. 60 sec for cached and
      • scheduled thread pool 
      • workQueue - task stored in this queue from where the thread fetches the task, 
      • threadFactory - use to create new threads, 
      • handler - this is used to handle the rejection
      • Naming a thread
      • Priority of a thread
      • ShutdownHook
      • Garbage collection

      • Synchronization - Synchronized method, Synchronized block, Static synchronization
      • Synchronized block

        • Synchronized block is more preferred way because it doesn’t lock the Object, synchronized methods lock the Object and if there are multiple synchronization blocks in the class, even though they are not related, it will stop them from execution and put them in wait state to get the lock on Object.
      • Concurrency

      • Atomic variable
      • Busy spin
      • Current thread
      • Cyclic barrier
      • CountDownLatch
      Context switching

      • It is the process of storing and restoring of CPU state so that Thread execution can be resumed from the same point at a later point of time. 
      • It is the essential feature for multitasking operating system and support for multi-threaded environment.

      Thread Slicing

      • It is the process to divide the available CPU time to the available runnable threads. 
      • Allocation of CPU time to threads can be based on thread priority or the thread waiting for longer time will get more priority in getting CPU time. 
      • Thread scheduling can’t be controlled by java, so it’s always better to control it from application itself.

      • Futuretask
      • Inter thread communication and Co-operation
      • Lockstriping
      • Pre-emptive scheduling & time slicing
      • Lock  - ReentrantLock, ReadWriteLock
      • Race condition
      • Semaphore
      • Shutdownhook
      • Thread Group, Thread variable, thread safe, thread dumb, thread exception
      • Volatile variable
      Thread dumb
      • Thread dump is list of all the threads active in the JVM,  To analyze a deadlock, we need to look at the java thread dump of the application, we need to look out for the threads with state as BLOCKED and then the resources it’s waiting to lock, every resource has a unique ID using which we can find which thread is already holding the lock on the object.

      Thread pool - It manages the collection of Runnable threads and worker threads execute Runnable from the queue.

      • FixedThreadPool - is the one which will have fixed number of threads. Each time a task is submitted its available in the  blocking queue which is thread safe. Once the task has been completed , the next task will be picked from the blocking queue for processing
      • CachedThreadPool - it will not have fixed number of thread and blocking queue.It will have synchronous queue, it can hold only one task at a time.
        • Once the task is created and available in the queue , it will check for the threads which is already created are free.
        • if the thread is free task is allocated else new thread will be created and task is allocated to it.
        • If the thread is idle for 60 seconds the thread will be killed.
      • ScheduledThreadPool - It uses a delayqueue
        • Service.scheduleAtFixedRate 
        • Service.ScheduleAtFixedDelay
        • schedulexecutorservice service = executors.newScheduledThreadPool(corepoolsize:10); 
        • service.schedule(new Task(), delay:10, seconds);
        • service.scheduleAtFixedRate(new Task(), initialdelay:15, period:10, seconds); 
        • Service.ScheduleAtFixedDelay(new Task(), initialdelay:15, dealy:10, timeunit.seconds); 

                                    • SingleThreadedExecutor - same as FixedThreadPool with blocking queue . But only one thread runs all the task.Recreates a thread if the thread is killed by the task.

                                    Constants

                                    • public static int MIN_PRIORITY
                                    • public static int NORM_PRIORITY
                                    • public static int MAX_PRIORITY
                                    • Default priority of a thread is 5 (NORM_PRIORITY). The value of MIN_PRIORITY is 1 and the value of MAX_PRIORITY is 10.

                                    Policy

                                    • AbortPolicy - Throws rejected exception at runtime, 
                                    • DiscardPolicy - discard the task silently without intimating the user, 
                                    • DiscardOldestpolicy - remove the oldest task and add the new task to the queue
                                    • CallerRunPolicy - if the task is rejected then the main thread itself will run the rejected task

                                      Difference

                                      • Producer vs consumer
                                      • InvokeAndWait vs InvokeLater

                                      No comments:

                                      Post a Comment

                                      Most views on this month