ContactUs :

Please send your Questions & Answers or Feedback to ""

How to make 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.



public class Counter {


    private int count;

    AtomicInteger atomicCount = new AtomicInteger( 0 );




     * This method thread-safe now because of locking and synchornization


    public synchronized int getCount(){

        return count++;




     * This method is thread-safe because count is incremented atomically


    public int getCountAtomically(){

        return atomicCount.incrementAndGet();





1) 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.

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

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

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


7) local 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.


9) 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.

Related Posts Plugin for WordPress, Blogger...
Flag Counter