Java Advanced Concurrency

1.     Why Executor framework is required?
It is not advisable to create N numbers of threads for each request. Creating new thread is more cost executive. Thread is created on demand by developer. 1000 of thread is created and killed.
Thread is created and died once work is over. JavaEE application you should not create thread at all
2.     Why Executor?
It is pool of threads to be used as on available.
In Java pool of Threads are the instance of executor.
It has only one method execute(Runnable)

ExecutorService we have another interface which Executor

ExecutorService executor = Executors.newSingleThreadExecutor();
Executor.execute(runnable);

All thread calls are asynchronous call

3.Thread life cycle
Task is added to waiting queue.
Task is executed on order queue

3.     Runnable Vs Callable in executor
Runnable: Can not know if task is executed or not
Some cases cancelling task is not possible in runnable
Method in runnable does not return anything
No exception raised
4.     What is Future object?
It is a bridge between executor and main thread

Public interface Callable<V>{
V call() throws exception;
}

To use callable we have to use ExecutorService submit()
5.     How future object work?
Once Executor finish the task it added the result to the Future object. The Future object type is same as callable type. Future.get() returns the value once task is finished. If task is not finished it will be blocked.

If anything goes wrong then 2 exception raised
1.     InterruptedException – if something happen in execution
2.     Task it self can raise exceotion. In that case get() warp it ExecutionException if any application exception
We can pass timeout in get() argument to block indefinitely.
6.     Shut down executor service
There are 3 methods
Shutdown() shutdown softly
shutdownNow() immediate shutdown. Not respectful
awaitTermination(Timeout) : Hybrid of soft and hard way of shutdown
  Using Locks and Semaphore

There are 2 uses of synchronization
1.     Synchronize block
2.     Volatile variable
Both are intrinsic locking
What are the problems of intrinsic locking?
In intrinsic locking we created a key object and lock the block of code with that key object. That means only one thread can execute that block of code at a time. If another thread there, it has to wait till the executing thread is finished. If more threads there to execute the block of threads all have to wait till the executing thread is finished. What will happen if the executing block got some exception and stuck in execution. So all the other waiting threads will be indefinitely in waiting state. There is no way of coming out of this situation except termination JVM which is very costly in nature.

What is Extrinsic locking and how it is beneficial?
This mechanism uses Lock interface and it’s implementation as ReentrantLock
There are lock() and unlock() there in Lock interface. Unlock() is called inside finally block. So whatever the case may be it will return to the calling thread.

What lock pattern brings to us?
It brings uninterruptible acquisition
The Lock interface has another method lockInterruptly() . Another thread can interupt it by calling its interupt() method. It is not possible using synchronization.

The lock pattern has another feature:
TimedLockAcquisation:

If thread is already executing the block of code then tryLock() will return false immediately. So instead of block, the thread can do some other task that time.

Threre can be a timeout parameter in tryLock(1,TimeUnit.second). In this case the thread will wait for 1 sec and if not get the lock then it do some other task in else block

What is FairLockAcquistion?

FairLockAcquisation means the thread which enters to waiting state first should execute the guarde block of code first. By deault both synchronization and explict lock are not fair lock. We can make it fair lock by passing  ‘true‘ in ReentrantLock() constructor

Lock lock = new ReentrantLock(true);

Implementing producer /Consumer pattern

 What is the problem with wait and notify method?
 If wait() is blocked . If no thread call notify or notifyAll then there is no way to resume the application

How to write producer and consumer problem using lock pattern?

What is Condition object?
Condition object is used to pass signal to the threads like wait and notify. But it is used in locking mechanism.
It is created from lock object

Condition condition = lock.newCondition();
Fairness lock will give fair conditions

There are 2 methods in Condition
await() and signal()

There are 5 versions of await()
await()
await(Time, timeUnit)
awaitNanos(nanotimeunit)
awaitUntil(date)
awaitUninterruptbly()

What is ReadWriteLock?
ReadWriteLock is an interfaces having 2 methods
readLock() – Multiple thread can hold readLock at a time
writeLock() – Only one thread can hold writeLock at a time
Both readLock() and writeLock() are instances of Lock

ReadWriteLock lock = new ReentrantReadWriteLock();
Lock readLock = lock.readLock();
Lock writeLock = lock.writeLock();

If we have many read anf few writes this lock is useful

What is Semaphore?

Semaphore is built on the number of permits. The number of permits are the number of threads allowed in the guarded code. The threads who having permit can enter into the guarded block of code

Semaphore semaphore = new Semaphore(5);

Try{
Semaphore.acquire(); // multiple permission can also acquire like semaphore.acquire(2) but in reelase also 2
//guarded code
}
Finally{
Semaphore.release() // if multiple permits acquire release should be also same number of permits

If a thread calls interrupted() acquire on block of code then it will throw interrupted exception. If we do not want to be interrupted then semaphore.acquireUninterruptbly() should call


tryAcquire() is check if permit can acquire 

No comments:

Post a Comment