Monday, 29 August 2011

How to make classes thread safe ?

What is Thread safety?
Thread safety is not making a class which implements Runnable or extends Thread, safe.  Thread safety means that the fields of an object or class always maintain a valid state as observed by other objects or classes when used concurrently by multiple threads.


What are the problems if you don't make a class thread safe?
Consider a scenario, where two threads are working on the same instance of the class. The object may be undergoing some modification in one thread and at the same time another thread may try to view the state of this object. This object when in thread1 could be in some intermediate state (when it is pre-empted) when thread 2 tries to access it. In this situation, thread 2 is viewing dirty state of the object. To make two threads, view a valid state of the object is when we term that an object is Thread safe.

When should you think about thread safety?
Firstly, you should think of thread safety whenever you are working in a multi-threaded application. Java allows multiple threads to be created, hence you think about it whenever you are coding in Java. When you have an instance of a class which can potentially be accessed in multiple threads when undergoing change in state, you should think about thread safety.
Secondly, as we know all threads share the same heap and memory area, it make it necessary to think about thread safety.

How can you achieve thread safety?
Remember? You would not think of thread safety if your object is immutable or is being used in read-only mode,reason: the state of the object cannot be changed or is not changed in these situations.
So, for sure,we know that making a class immutable (we will discuss in another article how to make a class immutable) or using it as read-only gives us thread safety.
But, there is a situation where you have to modify the state of the objects then you need to think of thread safety, synchronization the piece of code can help.
It may also happen that the code that is provided cannot be modified (could be a third party library or your boss does not allow you to play with a tried and tested code), you can still do it by extending the class and making a thread safe wrapper which can be used by the clients of your code. (Example , Collections are not thread safe, you can write thread safe wrapper for collections)


Points to remember when making the class thread safe
  • Synchronize only the critical code.
  • Instance and static variable are not thread safe, they exist on heap and memory area which multiple threads can access.
  • Local variables,parameters to methods are thread safe.
  • Synchronization comes with performance cost, so synchronize only whats is critical and not the entire method.
References:



No comments:

Post a Comment