Tuesday 4 April 2017

Multithreading (Java Concurrent API)

Concurrent API first introduced in Java 5. Java concurrent API is very useful if you writing multithreading code. These in built classes help programmers to handle lot of complex scenario with ease. It always recommended to use theses API classes instead of writing your own implementation.

Note: In this tutorial I'm not going to cover classes/interfaces of Concurrent API related to collection. I have discussed same in Collection tutorial. 

1. What are the concepts/features that has been introduced in Java 5 concurrent API.

AnswerJava 5 came up with following concepts/features under Concurrent API:
1. Lock API.
2. CountdownLatch.
3. CyclicBarier.
4. Semaphore.
5. Executor Framework.
6. Atomic variables.
7. Concurrent Collection classes.

1. Discuss Lock API in detail?

Answer: java.util.concurrent.Lock interface introduced in Java 5 to overcome the problems that we have with synchronized block. Functionality wise Lock interface behaves same as synchronized block but Lock interface is more sophisticated than synchronized block. 
Following features has been part of Lock interface which overcome the problem that we have with synchronized block :
1. Lock Interruptibly: lockInterruptibly() method defined in Lock interface that gives functionality that a thread can try to acquire the lock Interruptibly.
assume thread-1 is waiting outside synchronized section for a lock to become free which is already acquired by thread-2. Now if thread-2 takes long time to execute then thread-1 has to wait(sit idle) for lock to become free  for long time unnecessarily. 
In case of conventional lock there is no way that we can tell waiting thread(thread-1) to come out of waiting state i.e. we can not interrupt thread-1.
lockInterruptibly(), which try to acquire lock. if lock is not available then thread need to wait but thread can be interrupt by other thread. So thread won't go in an indefinite waiting state.
2. Fair Lock: Lock interface also ensure fair lock so all thread can get equal access to lock to avoid thread starvation.
Let's assume there are 5 thread running in an your application. Now at any given time say 3 thread waiting for a lock to become free. 
In case of conventional lock as soon as lock will become free, Thread scheduler will pick any waiting thread to assign lock. 
But Lock interface will assign the lock to the thread who is waiting for longest time or got very little time to access the lock compare to other threads.
3. Try lock: There are two methods available in Lock interface:
1. tryLock(): If a thread call tryLock() in order to acquire lock then thread will try to acquire the lock and if got it will return true otherwise false without getting blocked to get lock. 
1. tryLock(int time): It behaves same as tryLock() except in this case thread will wait till provided time for lock.

No comments:

Post a Comment