Skip to main content

How do I make my class thread safe

A class is thread safe when read and write operations on an object in multiple threads result in consistent, predictable behavior.

In this Q&A, we'll go over different ways one can make a class thread safe.
  1. Make the class stateless.  If the object does not have any state then they are thread safe
  2. Make the class immutable
  3. Use Atomic classes. Atomic classes atomically sets values in a lock free way if the current value matches expected value
  4. Use volatile keyword when declaring a variable.  Volatile keyword ensures that the object is fetched from memory always.  It ensures that object state modified by Thread 1 is always reflected in Thread 2.  See usage in ConcurrentHashMap class
  5. Use ThreadLocal.  ThreadLocal class provides ability to store state - in memory - that's accessible only from the current thread.  But be aware of the pros and cons
  6. Use synchronized keyword to synchronize access to the object.  See synchronized usage in SynchronizedCollection static class within Collections class.  .
  7. Use Locks.  Lock interface synchronized access to a critical section of code.  It also provides the ability to get read ( shared ) and write (exclusive ) locks .  See Lock usage here

Comments