Thursday, April 9, 2015

Thread Safety in Java

Thread safety is the process to make our program safe to use in multithreaded environment, there are different ways through which we can make our program thread safe. Concurrent programming is bounded by the norms of thread safety.

Code that is safe to call by multiple threads simultanously is called thread safe. If a piece of code is thread safe, then it contains no race conditions. Race condition only occur when multiple threads update shared resources. Therefore it is important to know what resources Java threads share when executing.

Each thread has its own stack. Two different threads never shares the same stack. All local variables defined in a method will be allocated memory in stack. As soon as method execution is completed by the current thread, stack frame will be removed. So, local variables are thread safe in Java. If an object created locally never escapes the method it was created in, it is thread safe.Local references to objects are a bit different. The reference itself is not shared. The object referenced however, is not stored in each threads's local stack.


  • Synchronization is the easiest and most widely used tool for thread safety in java.
  • Use of Atomic Wrapper classes from java.util.concurrent.atomic package. For example AtomicInteger
  • Use of locks from java.util.concurrent.locks package.
  • Using thread safe collection classes, i.e ConcurrentHashMap for thread safety.
  • Using volatile keyword with variables to make every thread read the data from memory, not read from thread cache.

No comments: