Monday, June 23, 2014

Pessimistic Vs Optimistic Approach for Thread Safety.

For concurrent environment, Where numbers of threads playing with objects than can be used by them concurrently, is a possible case for data race, or dirty read. Developing a thread safe program is a tedious task, specially when you have no support from the environment or compiler itself for handling such a thing.

What is more important for an algorithm to work, it’s correctness. If your program is not correct then it is of no use. Hence from a programmer point of view, they mostly give correctness more importance than it’s performance.

Pessimistic Approach for Thread Safety

In java, for developing a multithreaded concurrent program with correct behaviour in any condition, there are the concept of intrinsic or extrinsic locks. We generally prefer thread safe class which internally uses this locking mechanism to implement so that it can guarantee thread safety. You and me have used synchronized keyword as well as certain synchronization tools like, Lock, Semaphore etc for creating thread safe class. But creating a thread safe class using these locking mechanism, have certain disadvantages also, it degrades your program also. Acquiring a lock, makes the requesting thread to go in waiting state during that period the thread will no be able to do anything also, no of context switching is required to wake the suspended and block the executing thread. Context switching is a costly operation. Sometimes it happens where you have a thread with high priority, but that thread will not be able to execute bcz, other thread have already acquired that lock. Hence this approach is sometimes not good from performance point of view, where there is less likely to be any conflict between threads running concurrently.

Using synchronized classes like StringBuffer, HashTable and other’s are totally thread safe, which used intrinsic locking mechanism to provide thread safety is based on Pessimistic Approach, which doesn’t take risk to conflict happens between thread by denying to do not work concurrently.

Optimistic Approach for Thread Safety

Optimisic approach is more towards, let the things happen we wiil manage it, if things like conflict occur. The best thing about this Approach is it’s performance. But the point which we have to handle this is, how we are going to handle this thing, if such kind of conflict happens.

    There are no of techniques, has been using for developing multi-threaded concurrent thread safe programs. Some of the strategies are
  • Compare And Swap
  • Copy On Write
  • Extrinsic Locks on Segments

There are numbers of Thread safe classes has been provided by java, which are implemented using such kind of strategy. These classes are part of or depends on java.util.concurrent package of java, which provides the framework for developing thread safe programs without using the instrinsic lock (Pessimistic Approach).


1 comment: