Saturday, September 20, 2008

How do you write threead safe programs

Thread safe program is one which will work well in an environment where there are multiple threads working in tandem.

Look out for global variables. These can be easily in the centre of a conflict between multiple threads
Its a common practise to declare static constants. Such constants should be declared as final whenever possible.
This will gaurantee that these do not get changed
If you have an intention of changingthese- then they shouldnt have been Static Variables probably

Thread safe program is achieved by taking care of the following
1) Write re-entrant code
This involves using variables created on stack (private variables) rather than variables created on heap (global)

2) Mutual Exclusion
Access to shared data is serialized- typically by using programming constructs like synchronized in Java.

3) Atomic operation
Using machine language instructions

4)Thread local storage
Not sure if Java provides this.

No comments: