Monthly Archives: June 2015

Thread-safe code

Yes, just like every other programmer, I have been asked “Is this code thread safe?” and many times I have pondered in my head , what that actually means. Honestly I am not competent enough in multi-threading programming and even answering this question. But then there comes a time when you learn about this and say “Yes, the code is thread safe and it will execute correctly in case of simultaneous execution by multiple threads.”

Wikipedia says about thread-safety

“A piece of code is thread-safe if it only manipulates shared data structures in a manner that guarantees safe execution by multiple threads at the same time “

Most of the problems arise in multi-threaded environment when accessing shared data.

Here is an example of the code which can be safe in a single-threaded environment, but not in multi-threaded.

public class Counter
{
   private static int count = 0;
   public static int incrementCount()
   {
      return count++;
   }
}

count is a shared integer variable here. In a multi-threaded environment, it can lose the right value during the update operation. Increment operation for count performs read, add, and update. In case if two threads are accessing incrementCount method and not synchronized, they can cause the wrong value of count.

How to make this code thread-safe

public class Counter
{
   private static int count = 0;
   public static synchronized int incrementCount()
   {
      return count++;
   }
}

synchronized adds that mutual exclusion between threads while accessing incrementCount method. So at one time, only one thread can access the method. Instead of making the whole method synchronized, only part of the code can also be made synchronized.

Conclusion

I showed how we can write thread safe programming. If you enjoyed this post, subscribe to my blog. If you want to learn more about thread safety, read this post.