Showing posts with label Multithreading. Show all posts
Showing posts with label Multithreading. Show all posts

Tuesday, 9 May 2017

How deadlock happens and how to avoid it ?


DEADLOCK SITUATION
When two threads are waiting for each other to get the lock and stuck for infinite time.
Image result for deadlock

REASON BEHIND DEADLOCK
Multiple threads are not the real cause of deadlock, instead the way in which threads are requesting the lock.
 

HOW DEADLOCK HAPPENS ?
1. When using nested synchronized blocks
OR
2. When one synchronized method called from other


ANALYZING DEADLOCK
1. Take thread dump using kill -3
OR
2. Use jconsole
It will print which thread is locked on which object.


CODE TO REPRODUCE DEADLOCK
public void m1() {
  synchronized(String.class) {
      System.out.println("inside block for String"); 
      synchronized(Double.class) {
           System.out.println("inside block for Double");
      }
  }
}

public void m2() {
  synchronized(Double.class) {
      System.out.println("inside block for Double"); 
      synchronized(String.class) {
           System.out.println("inside block for String");
      }
  } }


FIXING OR AVOIDING DEADLOCK
  • Provide ordered access to the object using synchronized blocks.
Below example will not lead to any deadlock because both methods are accessing lock on String and Double classes in same order.

public void m1() {
  synchronized(String.class) {
      System.out.println("inside block for String"); 
      synchronized(Double.class) {
           System.out.println("inside block for Double");
      }
  }
}

public void m2() {
  synchronized(String.class) {
      System.out.println("inside block for String"); 
      synchronized(Double.class) {
           System.out.println("inside block for Double");
  
      }
  }
}

Sunday, 5 March 2017

Multithreading interview questions


Thread
Independent path of execution

Thread vs. Process
One process can contain multiple threads

How to implement thread ?
Thread class and Runnable interface   (Thread implements Runnable)
Runnable is better which provides opportunity to extend another class.



Use of Volatile
Every Thread has its own local memory for its instance variables.
We may alter the value of instance variable from any thread.
M
aking a variable volatile guarantees that the thread will also see any update done before initializing volatile variable.



start() vs. run()
Invoking run() will execute method but will not start a thread.

How to stop the thread ?
Thread will only stop once run method is finished and cannot be restarted once finished.
You can check a boolean instance variable in the loop inside your class extending Thread.
Example
private class MyThread extends Thread {
    boolean tExit = false;
 
    public void exit(boolean tExit) {
        this.tExit = tExit;
    }
 

    @Override
    public void run() {
        while(!tExit){
            // Your logic here...
        }
    }
}

Why should we make tExit variable volatile in above example ?
It is a good practice to make tExit volatile because any thread may alter the value of tExit.
Making it volatile guarantees that MyThread will also see any update done before initializing tExit.
Runnable vs. Callable
Callable's call() method can :

  • Return value (A Future object which can hold the result of computation)
  • Throw Exception

CyclicBarrier vs. CountDownLatch
Both waits for wait for number of threads on one or more events
We cannot re-use CountDownLatch once count reaches to zero, but you can reuse same CyclicBarrier even after barrier is broken



notify vs. notifyAll
notify() doesn't provide any way to choose a particular thread – useful when there is only one thread waiting
notifyAll() sends notification to all threads and allows them to compete for locks

Why wait, notify and notifyAll are not inside thread class ?

ThreadLocal variable
ThreadLocal variable is per thread. Stores local state of each thrad.

FutureTask
Base impl of Future interface
Have methods to :
·         methods to start and cancel a computation
·         query to see if the computation is complete
·         retrieve the result of the computation
interrupted() vs. isInterrupted()
interrupted is :
·         static method
·         clears the interrupt status (An internal flag)

How you can ensure the sequence of 3 threads ?
Use join()
Start from T3 , call join() so that it calls T2 , inside T2 call join() again so that it calls T1
By this way, the execution sequence would be T1 -> T2 -> T3

Concurrency level of ConcurrentHashMap
Partitions actual map into a number of sections (# sections = Concurrency level) , Default = 16 , Permits concurrent updates
What is Semaphore ?
It maintains a set of permits
acquire() blocks until a permit is available

Wednesday, 25 January 2017

Runnable vs. Callable



Callable's call() method can :
  • Return value : A Future object which can hold the result of computation
  • Throw Exception

CyclicBarrier vs. CountDownLatch




SIMILARITY
  • Both waits for number of threads on one or more events

DIFFERENCE
  • We cannot re-use CountDownLatch once count reaches to zero 
  • You can reuse same CyclicBarrier even after barrier is broken

How can you ensure the execution sequence of threads ?


Use join()

  • Start from T3
  • Call join() so that it calls T2
  • Inside T2, call join() again so that it calls T1


By this way, the execution sequence would be T1 -> T2 -> T3

Monday, 2 May 2016

What happens if a thread throws an exception inside synchronized block ?


No matter how you exits synchronized block, either normally by finishing execution or abruptly by throwing exception, thread releases the lock it acquired while entering that synchronized block.

What happens if you submit task, when queue of thread pool is already fill ?


ThreadPoolExecutor 's submit() method throws RejectedExecutionException if the task cannot be scheduled for execution.

What is concurrence level of ConcurrentHashMap in Java?


ConcurrentHashMap achieves its scalability and thread-safety by partitioning actual map into number of sectionsThis partitioning is achieved using concurrency level. 

It is optional parameter of ConcurrentHashMap constructor and it's default value is 16.

The table is internally partitioned to try to permit the indicated number of concurrent updates without contention.

Monday, 25 April 2016

sleep() vs. wait()


sleep() vs. wait()

CALLING LOCATION
wait() must be called from synchronized method / block
sleep() can be called from anywhere 

TARGET
wait() is instance specific method called on object (exists in Object class)
sleep() is static method called on thread (exists in Thread class) 

LOCKING
wait() releases the acquired lock when thread is waiting
Thread.sleep() keeps the lock even if thread is waiting

WAKE UP CONDITION
After wait() , thread will wake up when notify() or notifyAll() is called
After sleep() , thread will wake up when at least the time expires or call interrupt()

USAGE
sleep() is used to pause a Thread execution
wait() is used for Inter-thread communication