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.
- Make the class stateless. If the object does not have any state then they are thread safe
- Make the class immutable
- Use Atomic classes. Atomic classes atomically sets values in a lock free way if the current value matches expected value
- 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
- 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
- Use synchronized keyword to synchronize access to the object. See synchronized usage in SynchronizedCollection static class within Collections class. .
- 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
Post a Comment