Monday, May 1, 2017

How to make code Thread-Safe in Java

How to make code Thread-Safe in Java


There are multiple ways to make this code thread safe in Java:

1) Use synchronized keyword in Java and lock the getCount() method so that only one thread can execute it at a time which removes possibility of coinciding or interleaving.

2) use Atomic Integer, which makes this ++ operation atomic and since atomic operations are thread-safe and saves cost of external synchronization.

3) Immutable objects are by default thread-safe because there state can not be modified once created. Since String is immutable in Java, its inherently thread-safe.

4) Read only or final variables in Java are also thread-safe in Java.

5) Locking is one way of achieving thread-safety in Java.

6Static variables if not synchronized properly becomes major cause of thread-safety issues.

7) Example of thread-safe class in Java: Vector, Hashtable, ConcurrentHashMap, String etc.

8) Atomic operations in Java are thread-safe e.g. reading a 32 bit int from memory because its an atomic operation it can't interleave with other thread.

9local variables are also thread-safe because each thread has there own copy and using local variables is good way to writing thread-safe code in Java.

10) In order to avoid thread-safety issue minimize sharing of objects between multiple thread.

11) Volatile keyword in Java can also be used to instruct thread not to cache variables and read from main memory and can also instruct JVM not to reorder or optimize code from threading perspective.