Showing posts with label thread interview questions with answers. Show all posts
Showing posts with label thread interview questions with answers. Show all posts

Monday, 10 June 2019

Object-Level and Class-Level Locks in Java with Examples

         This is an important interview question for experienced Java developers, as it tests their understanding of the different types of locks used in multithreading.

As we know, Java supports the concurrent execution of multiple threads. When two or more threads access the same shared resource simultaneously, it can lead to data inconsistency or race conditions. To avoid these issues, Java provides the synchronization mechanism, which ensures that only one thread can access a shared resource at a time while other threads wait for their turn.

Synchronization is achieved using the synchronized keyword, which can be applied at either the method level or the block level.

There are two types of locking in Java multithreading:

  • Object level lock
  • Class level lock

Object level lock:-

         Object level locking is about synchronizing a non-static method or non-static code block such that only one thread will execute the code block on given instance of the class. Object level locking make instance level data thread safe.

There are different ways we can lock the object in thread as below,

public class ThreadClassEx {
      
       public synchronized void syncMethod(){
             //method implementation here
       }
}

public class ThreadClassEx {
      
       public void syncMethod(){
           
              synchronized(this) {
                  //block implementation here
              }
       }
}

public class ThreadClassEx {
      
         private final Object lock = new Object();

         public void syncMethod(){
           
                   synchronized(lock) {
                           //block implementation here
                   }
          }
}


Class level lock:-

         Class level locking is about a synchronizing a static method or block so that it can be accessed by only one thread for whole class. If you have 100 instances of class, only one thread will be able to access only one method or block of any one instance at a time.

        This should always be done to make static data thread safe.

Various ways of class level locking is as follows,

public class ThreadClassEx {

      public synchronized static void syncMethod(){
               //method implementation here
      }
}

public class ThreadClassEx {

      public void syncMethod(){
         
            synchronized(ThreadClassEx.class) {
               //block implementation here
            }
      }
}

public class ThreadClassEx {

      private final static Object lock = new Object();

      public void syncMethod(){
         
            synchronized(lock) {
               //block implementation here
            }
      }
}

Thank you for visiting blog.


Related Posts:-
1) Producer Consumer Problem - Solution using wait and notify In Java
2) Thread join() method example in Java
3) Difference between the Runnable and Callable interface in Java
4) Explain Thread life cycle and difference between wait() and sleep() method.
5) How many ways to create a thread in Java? Which one Prefer and why?
6) Producer Consumer Problem - Solution using BlockingQueue in Java

Wednesday, 14 March 2018

Java Thread join() Method with Examples

           The join() method of the java.lang.Thread class is used to pause the execution of the current thread until the specified thread has finished executing.

The Thread class provides the following three overloaded join() methods:

  • join()

          This java thread join method puts the current thread on wait until the thread on which it’s called is dead. If the thread is interrupted, it throws InterruptedException.

  • join(long milisecond)

          This java thread join method is used to wait for the thread on which it’s called to be dead or wait for specified milliseconds. Since thread execution depends on OS 
implementation, it doesn’t guarantee that the current thread will wait only for given time.

  • join(long millisecond, int nanosecond)

          This java thread join method is used to wait for thread to die for given milliseconds 
plus nanoseconds.

join example,

JoinExample.java,

package com.practice;

public class JoinExample {
     
      public static void main(String[] args) {
            Thread t1 = new Thread(new MyClass(), "thread1");
            Thread t2 = new Thread(new MyClass(), "thread2");
            Thread t3 = new Thread(new MyClass(), "thread3");
         
            t1.start();
            try {
                t1.join();
            } catch (InterruptedException ex) {
            }
      
            t2.start();
            try {
                t2.join();
            } catch (InterruptedException ex) {
            }
      
            t3.start();   
            try {
                 t3.join();
            } catch (InterruptedException ie) {
            }  
      }
}
 
class MyClass implements Runnable{
 
    @Override
    public void run() {
      Thread t = Thread.currentThread();
         System.out.println("Thread started:- "+t.getName());
         try {
              Thread.sleep(1000);
         } catch (InterruptedException ex) {
              ex.printStackTrace();
         }
         System.out.println("Thread ended:- "+t.getName());
        
    }
}

Output:--Thread started:- thread1
                 Thread ended:- thread1
                 Thread started:- thread2
                 Thread ended:- thread2
                 Thread started:- thread3
                 Thread ended:- thread3



Related Post:--

Sunday, 24 September 2017

Difference between the Runnable and Callable interface in Java

        This is also one of the important question of Java interview for middle level developer.  Runnable interface is added in JDK 1.0 where as Callable was added much later i.e in Java 5, along with many other concurrent features CopyOnWriteArrayList, ConcurrentHashMap, BlockingQueue and ExecutorService .
       
        If you see basic functionality both Callable and Runnable interfaces are implemented by any class whose instances are to be executed by another thread.  Callable interface have a some extra features which were not there in Runnable.  Those features are,
  • Callable can return value
  • It can throw exception 

Difference between Runnable and Callable:--


1)  The Callable and Runnable are interfaces and both have a single method but that method and it's signature is different.


Runnable:-

   public interface Runnable {
               public abstract void run();
     }

Callable :

   public interface Callable<V> { 
               V call() throws Exception;
     }


2)  Callable interface is a part of the java.util.concurrent package whereas Runnable interface is a part of the java.lang package.

3)  If you have noticed the signature of call method in the callable interface, you can see that call method can return value


      V call() throws Exception

  
     In the above code, V is the computed result.  Callable is a generic interface and type is provided at the time of creating an instance of Callable implementation.

Example:-

   Callable<Integer> callableObj = new    Callable<Integer>() {
          @Override
          public Integer call() throws Exception {
               return 2;
          }
    };

run() method of Runnable interface doesn't return any value,  return type is void. 

  @override
    public void run() {
         //does not return anything
    }
 
 
4)  Another difference that can be noticed from the signatures of the call() and run() method is that you can not give a exception with throws clause in run method.

  This below statement will give compile time error,

    public void run() throws InterruptedException
 
In call() method exception can be given with throws clause, as below.

    public Integer call() throws InterruptedException



5)  In order to run runnable task options are ,
  • Thread class has a constructor that takes Runnable as parameter.
  • Executor interface has execute method which takes Runnable as parameter.
  • ExecutorService has submit method which takes Runnable as parameter.
For Callable,
  • Thread class doesn't have any constructor that takes Callable as a parameter.
  • ExecutorService has submit method which takes Callable as a parameter.
  • ExecutorService also has invokeAll and invokeAny methods that takes Callable as a parameter.
  • Executors class has callable method that can convert Runnable to Callable 
    Callable callable = Executors.callable(Runnable task); 



Related Posts:-
1) How many ways to create a thread in Java? Which one Prefer and why?
2) Explain Thread life cycle and difference between wait() and sleep() method
3) Deadlock in Java multithreading - Program to generate the Deadlock and to avoid Deadlock in Java
4) Thread join() method example in Java
5) Producer Consumer Problem - Solution using wait and notify In Java

Friday, 6 June 2014

Thread(or Multithread) Interview Questions and Answers

 

1) What is Race Condition in Multithreading?

         A race condition occurs when two or more threads can access shared data and they try to change it at the same time. Because the thread scheduling algorithm can swap between threads at any time, you don't know the order in which the threads will attempt to access the shared data. Therefore, the result of the change in data is dependent on the thread scheduling algorithm, i.e. both threads are "racing" to access/change the data.(This condition will arise in multi threading).

             So, let’s get into the actual problem. Let’s say that there’s a husband and wife - Ramesh and Savita - who share a joint account. They currently have Rs.2,000 in their account. They both log in to their online bank account at the same time, but from different locations.
They both decide to deposit Rs.500 each into their account through a wire transfer from other bank accounts that they have at the same time. So, the total account balance after these 2 deposits should be Rs.2,000 + (Rs.500 * 2), which equals Rs.3,000.
              Let’s say Ramesh’s transaction goes through first, but Ramesh's thread of execution is switched out (to Savita’s transaction thread) right after executing this line of code in the deposit method:

    updatedBalance = accountBalance + depositedAmount ;

       
Now, the processor is running the thread for Ramesh, who is also 
depositing Rs.500 into their account.  When Ramesh’s thread deposits Rs.500, 
the account balance is still only Rs2,000, because the variable accountBalance
 has not yet been updated in Savita’s thread.  Remember that Savita’s thread
 stopped execution right before the accountBalance variable was updated.

         So, Ramesh’s thread runs until it completes the deposit function, and then updates the value of the accountBalance variable to $2,500. After this, control returns to Savita’s thread, where updatedBalance has the value of Rs.2,500. Then, it just assigns this value of Rs.2,500 to accountBalance and returns. And that is the end of execution.
                 What is the result of these 2 deposits of Rs.500? Well, the accountBalance variable ends up being set to only Rs.2,500, when it should have been Rs.5,000. This means Ramesh and Savita lost Rs.500. This is good for the bank, but a huge problem for Ramesh and Savita, and any other of the bank's customers.

     To avoid Race Condition you can use Synchronization i.e lock one thread and access only one thread. If released the previous lock then second thread can access the resource.

2) What is difference between Thread and Prcoess in Java?


1) Both process and thread are independent path of execution but one process can have multiple threads.
2) Threads are called as a task or light weight process in operating system.
3)  Every process has its own memory space, executable code and unique process identifier while every thread has its own stack in java but it use to process main memory and share it with other threads.

 

3) Why Thread is faster compare to process?

         A thread is never faster than a process. If you run a thread(say there’s a process which has spawned only one thread) in one JVM and a process in another and that both of them require same resources then both of them would take same time to execute. But, when a program/Application is thread based(remember here there will be multiple threads running for a single process) then definitely a thread based application/program is faster than a process based application. This is because, when ever a process requires or waits for a resource CPU takes it out of the critical section and allocates the mutex to another process.
            
            Before De-allocating the earlier one, it stores the context(till what state did it execute that process) in registers. Now if this De-allocated process has to come back and execute as it has got the resource for which it was waiting, then it can’t go into critical section directly. CPU asks that process to follow scheduling algorithm. So this process has to wait again for its turn. While in the case of thread based application, the application is still with CPU only that thread which requires some resource goes out, but its co threads(of same process/application) are still in the critical section. Hence it directly comes back to the CPU and does not wait outside. Hence an application which is thread based is faster than an application which is process based.

            Be sure that its not the competition between thread and process, its between an application which is thread based or process based.

4)  What is Synchronization? Explain with example.

          Synchronization is a process of controlling the access of shared resources by the multiple threads in such a manner that only one thread can access one resource at a time. In non synchronized multi threaded application, it is possible for one thread to modify a shared object while another thread is in the process of using or updating the object's value. Synchronization prevents such type of data corruption.

E.g. Synchronizing a function:
             public synchronized void Method1 () {
                      // Appropriate method-related code.
             }
E.g. Synchronizing a block of code inside a function:
            public myFunction (){
                  synchronized (this) {
                         // Synchronized code here.
                  }
           }

5)  Why wait,notify and notifyAll are in object class?

   
             Wait and notify is not just normal methods or synchronization utility,  more than that they are communication mechanism between two threads in Java. And Object class is correct place to make them available for every object if this mechanism is not available via any java keyword like synchronized.
              Locks are made available on per Object basis, which is another reason wait and notify is
declared in Object class rather then Thread class.
              In Java in order to enter critical section of code, Threads needs lock and they wait for lock, they don't know which threads holds lock instead they just know the lock is hold by some thread and
they should wait for lock instead of knowing which thread is inside the synchronized block and asking them to release lock. this analogy fits with wait and notify being on object class rather than thread in Java.


6) What is daemon thread in java?


         A daemon thread is a thread that is considered doing some tasks in the background like handling requests or various chronjobs that can exist in an application.
         When your program only have damon threads remaining it will exit. That's because usually these threads work together with normal threads and provide background handling of events.
         You can specify that a Thread is a daemon one by using setDaemon method, they usually don't exit, neither they are interrupted.. they just stop when application stops. 
Garbage Collection is a good example of  Daemon thread.


7)  What are the different states of Thread's life cycle ?

          There are five states of Thread's life cycle, as New, Runnable, Running, Blocked and Dead states. For more details please go through this link Explain Thread life cycle and difference between wait() and sleep() method

8)  What are the possible ways of creating Thread in Java?

      There are two possible ways to create thread in  Java. One is by extending java.lang.Thread class and other is by implementing Runnable interface. For more details, Please go through this link How many ways to create a thread in Java? Which one Prefer and why?

9) Once a thread has been started can it be started again?       

       No. Only a thread can be started only once in its lifetime. If you try starting a thread which has been already started once an IllegalThreadStateException is thrown, which is a run time exception. A thread is in runnable state or dead thread can not be restarted.


10)  Which thread related methods are available in Object class?


       There are three thread related methods are available in Object class,
1) public final void wait() throws InterruptedException
2) public final void notify()
3) public final void notifyAll()


11) What is a volatile keyword? 


         In general each thread has its own copy of variable, such that one thread is not concerned with the value of same variable in the other thread. But sometime this may not be the case. Consider a scenario in which the count variable is holding the number of times a method is called for a given class irrespective of any thread calling, in this case irrespective of thread access the count has to be increased so the count variable is declared as volatile.

        The copy of volatile variable is stored in the main memory, so every time a thread access the variable even for reading purpose the local copy is updated each time from the main memory. The volatile variable also have performance issues.



12) When jvm strats up, which thread will be started up first?

        When jvm starts up the thread executing main method is started. 


13) What will happen if we don't override the run() method of thread?

        When we call start() method on thread , internally it will call run() method to create the thread. If we don't override the run() method , won't be called and nothing will happen. 


           class MyThread extends Thread {
                       // don't override the run() method
           }

           public class MainClass {

                    public static void main(String[] args) {
                             System.out.println("Main thread has started");
                             MyThread thread = new MyThread();
                             thread.start();
                             Sysstem.out.println("Main thread end");
                   }
         }

output: Main thread has started
            Main thread end
        

14)  Producer Consumer Problem - Solution using wait and notify In Java 

For this question I have written separate post, go through this Producer and consumer solution using wait and notify

 

15) Producer Consumer Problem - Solution using BlockingQueue In Java 

For this question I have written separate post, go through this Producer and consumer solution using BlockingQueue


16)  What are the differences between Runnable and Callable interface in Java?    
    For this question I have written separate post, go through this  Difference between the Runnable and Callable interface in Java


17) Deadlock in Java multithreading - Program to generate the Deadlock and to avoid Deadlock in Java.

              In Java multi-threading, Deadlock is a situation where minimum two threads are holding lock on different resource and both are waiting for others resource to complete it's task. And both threads can hold lock forever and none of them complete it's task.  For details refer Program to generate deadlock in Java


18) Difference between Callable and Runnable interface in Java.

Refer Difference between Runnable and Callable interface.


Tuesday, 3 June 2014

Thread Life Cycle in Java and the Difference Between wait() and sleep() Methods

First, let's understand the concepts of Process and Thread. Once we have a clear understanding of these concepts, we can discuss the Thread Life Cycle in Java.

Process:--
         An executing instance of a program is called a process. Each process has its own address space (memory space) and can contain one or more threads.

Example:

If you open multiple instances of a Calculator application, each running instance is considered a separate process. Each process has its own memory and resources allocated by the operating system.


Thread:--
  
Threading is a mechanism that allows multiple tasks or activities to execute concurrently within a single process. Most modern operating systems support multithreading, and the concept of threads has existed in various forms for many years. Java was one of the first mainstream programming languages to provide built-in support for multithreading, rather than relying solely on the underlying operating system.

Threads are often referred to as lightweight processes. Similar to processes, threads represent independent paths of execution within a program. Each thread has its own stack, program counter, and local variables. However, unlike separate processes, threads within the same process share resources such as memory, file handles, and other process-level data.

        Because threads share the same memory space, communication between them is more efficient than communication between separate processes. However, this shared access also introduces challenges such as synchronization and thread safety, which must be handled carefully.



Thread Life Cycle:-

A thread can be in one of the following states ,
  1. New born state(New)
  2. Ready to run state (Runnable)
  3. Running state(Running)
  4. Blocked state
  5. Dead state

Thread Life Cycle
Thread Life Cycle In Java


New Born State:--

  • A thread enters the New (Newborn) state as soon as it is created using the new operator.

  • From the New state, the thread can transition to either the Runnable (Ready-to-Run) state or the Dead (Terminated) state.
  • When the start() method is called, the thread moves to the Runnable state, where it becomes eligible for execution by the thread scheduler.

  • If the thread is terminated before execution, it enters the Dead state.

Note: The stop() method has been deprecated and should not be used in modern Java applications because it can leave shared resources in an inconsistent state.



Ready to run mode (Runnable Mode):--
  • If the thread is ready for execution but waiting for the CPU the thread is said to be in ready to run mode. 
  • All the events that are waiting for the processor are queued up in the ready to run mode and are served in FIFO manner or priority scheduling.
  • From this state the thread can go to running state if the processor is available using the scheduled( ) method. 
  • From the running mode the thread can again join the queue of runnable threads. 
  • The process of allotting time for the threads is called time slicing.


Running State:--

  • If a thread is currently being executed by the CPU, it is said to be in the Running state.

  • A thread may complete its task and terminate normally after finishing its execution.
  • A running thread may also be forced to relinquish control and move out of the Running state when one of the following conditions occurs:

  1. A thread can be suspended by suspend( ) method. A suspended thread can be revived by using the resume() method.
  2. A thread can be made to sleep for a particular time by using the sleep(milliseconds) method. The sleeping method re-enters runnable state when the time elapses.
  3.  A thread can be made to wait until a particular event occur using the wait() method, which can be run again using the notify( ) method.

Blocked State:--
  • A thread is said to be in blocked state if it prevented from entering into the runnable state and so the running state.
  • The thread enters the blocked state when it is suspended, made to sleep or wait. 
  • A blocked thread can enter into runnable state at any time and can resume execution.
Dead State:--
  • The running thread ends its life when it has completed executing the run() method which is called natural dead. 
  • The thread can also be killed at any stage by using the stop( ) method.


Difference between wait() and sleep() methods in Java:
  1. The wait() method can be called only from a synchronized context (a synchronized method or block), whereas the sleep() method can be called from any context and does not require synchronization.

  2. The wait() method is defined in the Object class and is called on an object, whereas the sleep() method is defined in the Thread class and is called on a thread.

  3. A thread that is waiting using wait() can be awakened by another thread using the notify() or notifyAll() methods. In contrast, a sleeping thread cannot be awakened using notify() or notifyAll(); it wakes up only after the specified sleep time expires or if it is interrupted.

  4. The wait() method is typically used for inter-thread communication, where a thread waits until a specific condition becomes true. The sleep() method is used simply to pause the execution of the current thread for a specified period.

  5. When a thread calls wait(), it releases the lock (monitor) on the object and enters the waiting state. However, when a thread calls sleep(), it does not release any locks it holds during the sleep period.


Related Post:-
Thread(or Multithread) interview questions & answers