---
title: Writing Thread-Safe Programs Using Atomic Variables
description: Writing Thread-Safe Programs Using Atomic Variables
---

[![e-Zest logo\_An accion lab company\_Colour](https://blog.e-zest.com/hubfs/images/Logos%20with%20Tagline/Corporate/SVG/e-Zest%20logo_An%20accion%20lab%20company_Colour.svg "e-Zest logo_An accion lab company_Colour")](https://www.e-zest.com/)

- [WORK](https://www.e-zest.com/our-work)
- [SERVICES](https://www.e-zest.com/our-services) 
    - [Product Engineering](https://www.e-zest.com/digital-product-engineering-services)
    - [Enterprise Data Services](https://www.e-zest.com/enterprise-data-services)
    - [Digital Commerce](https://www.e-zest.com/digital-commerce-services)
    - [Digital Operations](https://www.e-zest.com/digital-operations)
    - [Digital Consulting](https://www.e-zest.com/digital-transformation-consulting-services)
    - [Digital Experience Design](https://www.e-zest.com/digital-experience-design)
- [INSIGHTS](https://blog.e-zest.com/)
- [CAREERS](https://www.e-zest.com/careers)
- [ENTERPRISE DATA SERVICES](https://www.e-zest.com/enterprise-data-services)
- [GENERATIVE AI](https://www.e-zest.com/generative-ai)
- [Healthcare](https://healthcare.e-zest.com)
- [Contact Us](https://www.e-zest.com/contact-us)

- ![Elevating Product Engineering with AI and ML](https://blog.e-zest.com/hubfs/Elevating%20Product%20Engineering%20with%20AI%20and%20ML.jpg)

  [BLOGS](https://blog.e-zest.com)
  
  #### Elevating Product Engineering with AI and ML

  As technology evolves and customer choices broaden, there is an increasing ...

  [Read more](https://blog.e-zest.com/elevating-product-engineering-with-ai-and-ml)
- ![e-Zest – An Accion Labs Company gets Recognition as a Contender in the ISG Provider Lens™ Study on Digital Engineering Services 2024](https://blog.e-zest.com/hubfs/e-Zest%20%E2%80%93%20An%20Accion%20Labs%20Company%20-%20Gets%20Recognition%20as%20a%20Contender%20in%20the%20ISG%20Provider%20LensTM%20Study%20on%20Digital%20Engineering%20Services%202024.jpg)

  [NEWS](https://blog.e-zest.com/news)
  
  #### e-Zest – An Accion Labs Company gets Recognition as a Contender in the ISG Provider Lens™ Study on Digital Engineering Services 2024

  We are delighted to announce that e-Zest – An Accion Labs Company has been ...

  [Read more](https://blog.e-zest.com/news/e-zest-an-accion-labs-company-gets-recognition-as-a-contender-in-the-isg-provider-lens-study-on-digital-engineering-services-2024)
- ![e-Zest Solutions supports Digital Pune Mission](https://blog.e-zest.com/hubfs/blog-files/Digital%20Literacy%20Bus%20e-Zest.png)

  [CSR](https://blog.e-zest.com/csr)
  
  #### e-Zest Solutions supports Digital Pune Mission

  **Pune, India:** e-Zest Solutions, a leading digital technology innovation ...

  [Read more](https://blog.e-zest.com/csr/e-zest-solutions-supports-digital-pune-mission)

- [Work](https://www.e-zest.com/our-work)
- [Services](https://www.e-zest.com/our-services)
- [Insights](https://blog.e-zest.com)
- [Careers](https://www.e-zest.com/careers)
- [Enterprise Data](https://www.e-zest.com/enterprise-data-services)
- [Generative AI](https://www.e-zest.com/generative-ai)
- [Innovations](https://www.e-zest.com/innovations)
- [Healthcare](https://healthcare.e-zest.com)
- [About](https://www.e-zest.com/about-us)
- [Contact](https://www.e-zest.com/contact-us)

- [Blog](https://blog.e-zest.com/)
- [News](https://blog.e-zest.com/news)
- [CSR](https://blog.e-zest.com/csr)

- [![Linkedin Icon](https://blog.e-zest.com/hubfs/icons/linkedin_icon_white.svg)](https://www.linkedin.com/company/e-zest-solutions/)
- [![Twitter Icon](https://blog.e-zest.com/hubfs/twitter-logo-silhouette%20(5).svg)](https://twitter.com/ezest)
- [![Facebook Icon](https://blog.e-zest.com/hubfs/facebook-app-logo%20(4).svg)](https://www.facebook.com/61259256638)
- [![Instagram Icon](https://blog.e-zest.com/hubfs/instagram-logo%20(4).svg)](https://www.instagram.com/ezestsolutions/)
- [![Youtube Icon](https://blog.e-zest.com/hubfs/icons/youtube_icon_white.svg)](https://www.youtube.com/user/ezestcorporate)

[![Go to top icon](https://blog.e-zest.com/hubfs/AA%20Assets/top%20button.svg)](https://blog.e-zest.com/writing-thread-safe-programs-using-atomic-variables/#top)

Hit enter to search or ESC to close

Insights

e-Zest members share technology ideas to foster digital transformation.

- [Blog](https://blog.e-zest.com)
- [News](https://blog.e-zest.com/news)
- [Podcasts](https://www.e-zest.com/podcasts)
- [Healthcare](https://blog.e-zest.com/healthcare)
- [CSR](https://blog.e-zest.com/csr)
- [Whitepaper](https://blog.e-zest.com/whitepaper)
- [Playbook](https://blog.e-zest.com/playbook)
- [Media Kit](https://www.e-zest.com/media-kit)

# Writing Thread-Safe Programs Using Atomic Variables

[Madhura Oak](https://blog.e-zest.com/author/madhura-oak)  May 09, 2012

[Thread-Safe Programs](https://blog.e-zest.com/topic/thread-safe-programs) [Java SE 5](https://blog.e-zest.com/topic/java-se-5) [Java](https://blog.e-zest.com/topic/java) [Multithreading](https://blog.e-zest.com/topic/multithreading) [Atomic Variables](https://blog.e-zest.com/topic/atomic-variables) [Technology](https://blog.e-zest.com/topic/technology)

- <https://www.linkedin.com/shareArticle?mini=true&url=https://blog.e-zest.com/writing-thread-safe-programs-using-atomic-variables/&title=&summary=&source=>
- <https://twitter.com/intent/tweet?source=https://blog.e-zest.com/writing-thread-safe-programs-using-atomic-variables/&text=Writing%20Thread-Safe%20Programs%20Using%20Atomic%20Variables>
- <https://www.facebook.com/sharer/sharer.php?u=https://blog.e-zest.com/writing-thread-safe-programs-using-atomic-variables/>
- <https://www.instagram.com/ezestsolutions/?u=https://blog.e-zest.com/writing-thread-safe-programs-using-atomic-variables/>

*Race condition* never occurs in a thread-safe program. What is a *race condition*? When variables are shared by multiple threads, there is a possibility that more than one thread get access to a variable and try to modify its value at the same time. This could lead to a loss of data modification done by a thread and leave the program in an inconsitent state. Such hazards should be avoided by allowing only one thread to access the shared variables when they are being modified. Synchronized methods and synchronized blocks are used to lock an object so that only one thread can access the object’s state and other threads keep waiting for the access until the lock is released.

Java SE 5 has introduced a package *java.util.concurrent.atomic* which offers lock-free and thread-safe classes. Variables of these class types are called as *atomic variables*. There are 12 classes within this package. The operations provided by these classes are not only atomic but also volatile. The modifications done to atomic variables by a thread are immediately visible to other threads.

If you need to implement an integer counter in your class as shown in Listing 1 then you can use atomic variables instead of implementing the synchronized methods.

```
private int count;

public int getCount() {
      return count;
}

public synchronized void increment() {
      count++;
}

public synchronized void decrement() {
      count--;
}
```

Listing 1. An integer counter

The above counter can be implemented using java.util.concurrent.atomic.AtomicInteger as shown in Listing 2.

```
private AtomicInteger count = new AtomicInteger(); //initial value is 0

public int getCount() {
      return count.get();
}

public void increment() {
      count.incrementAndGet();
}

public void decrement() {
      count.decrementAndGet();
}
```

Listing 2. Counter using AtomicInteger

If the piece of code in Listing 1 is just a part of your class or you put this code in a separate class, then the thread executing the `increment()` or `decrement()` methods would lock the entire object (instance of your class), thus preventing other threads from accessing the object, leading to thread contention. This way of obtaining exclusive lock by a thread is a *pessimistic* approach. A high-priority thread can keep waiting to obtain a lock on the object’s monitor, if another thread has locked it, leading to *priority inversion*. This is a disadvantage of locking.

**Compare and Swap (CAS)**  
 Most processors provide a *compare-and-swap* (CAS) instruction. The CMPXCHG instruction is used in Intel processors to perform CAS. In some processors such as PowerPC, CAS is achieved by *load-linked* and *store-conditional* instructions. A CAS is an atomic read-modify-write instruction which checks a memory location for a value and when found replaces it with a new value. Irrespective of whether the value is changed or not, it returns the value in the memory location. The CAS performance of processors will keep increasing in the coming years.

When atomic variables are used, the JVM calls these native *compare-and-swap* or *load-linked/store-conditional* instructions of the hardware processor. These classes provide a method *compareAndSet(oldValue,newValue)*.

An alternative way to write the `increment()` method of Listing 2 using `compareAndSet()` is given in Listing 3. When multiple threads attempt to update the count only one thread succeeds but the other threads are not blocked. They can retry updating the count. This is an *optimistic* approach. Such algorithms are called as *lock-free* because there is no lock obtained by a thread. This is also a *nonblocking* algorithm since the suspension or failure of one thread does not cause suspension or failure of other thread.

```
public void increment() {
      boolean valueChanged = false;
      while(!valueChanged) {
            int currentVal = count.get();
            int nextVal = currentVal + 1;
            if(count.compareAndSet(currentVal,nextVal)) {
                  valueChanged = true;
            }
      }
}
```

Listing 3. Non-blocking CAS approach

In non-blocking CAS approach, the program takes care of contention by retrying. In cases of extreme contention, this non-blocking CAS approach can lead to a livelock. However, non-blocking CAS-based counters using atomic variables have better performance than lock-based counters in low to moderate contention.

When locking is used as in Listing 1, the JVM needs to interact with the operating system to perform thread suspension, context switches and locking. The code in Listing 2 may appear complex but it is executed faster by the JVM since the instructions of the processor are directly used.

**AtomicInteger and AtomicLong**  
 The `java.util.concurrent.atomic.AtomicInteger` and `java.util.concurrent.atomic.AtomicLong` extend `java.lang.Number`. They wrap the primitive int and long value respectively. The following methods are provided by these classes:

- `get()` – Returns the current value
- `set(value)` – Sets the given value
- `getAndSet(newValue)` – Set the new value and return old value
- `incrementAndGet()` – Increments the value by 1 and returns the new value
- `decrementAndGet()` – Decrements the value by 1 and returns the new value
- `getAndIncrement()` – Increments the value by 1 and returns the old value
- `getAndDecrement()` – Decrements the value by 1 and returns the old value
- `addAndGet(value)` – Adds the given value to the current value and returns the updated value
- `getAndAdd(value)` - Adds the given value to the current value and returns the previous value

Unlike `java.lang.Integer` and `java.lang.Long`, AtomicInteger and AtomicLong are mutable and hence should not be used as a key in hash based collections.

In my last blog post, I had written about the [cache implementation to store the frequently searched programs](https://blog.e-zest.com/blog/writing-thread-safe-programs-using-concurrenthashmap/). One strategy to implement a fixed size cache is to maintain the search frequency of a program in a counter and when the cache size exceeds the maximum allowed size, the programs with least search frequency can be removed from the cache. The `ProgramSearchResult` class show in Listing 4, encapsulates the program and the search counter.

```
public class ProgramSearchResult {
      private Program program;
      private AtomicLong count = new AtomicLong(); //initial value 0

      public Program getProgram() {
            return program;
      }

      public void setProgram(Progam program) {
            this.program = program;
      }

      public long getCount() {
            return count.get();
      }

      public void setCount(long value) {
            count.set(value);
      }

      public void incrementCount() {
            count.incrementAndGet();
      }
}
```

Listing 4. Class to store searched program and the search count

I will be writing more about the above cache implementation in my next blog post.

- <https://twitter.com/intent/tweet?source=https://blog.e-zest.com/writing-thread-safe-programs-using-atomic-variables/&text=Writing%20Thread-Safe%20Programs%20Using%20Atomic%20Variables>
- <https://www.facebook.com/sharer/sharer.php?u=https://blog.e-zest.com/writing-thread-safe-programs-using-atomic-variables/>
- <https://www.linkedin.com/shareArticle?mini=true&url=https://blog.e-zest.com/writing-thread-safe-programs-using-atomic-variables/&title=&summary=&source=>

### Similar Blog

[Writing Thread-Safe Programs – Analyze Cost Of Locking One way of writing a thread-safe class is to use synchronization when its shared variables are being modified so that a lock is ... By Madhura Oak May 15, 2012](https://blog.e-zest.com/writing-thread-safe-programs-analyze-cost-of-locking/)

[Writing Thread-Safe Programs Using ConcurrentHashMap When your program can be accessed by multiple threads concurrently, you need to ensure that it is thread-safe. What is thread ... By Madhura Oak May 02, 2012](https://blog.e-zest.com/writing-thread-safe-programs-using-concurrenthashmap/)

[Oracle NoSQL Database (ONDB) Relational databases have been around us for more than 20 years now. Needless to say, they are mature and an obvious choice for ... By Madhura Oak Dec 24, 2013](https://blog.e-zest.com/oracle-nosql-database-ondb/)

[Session State Isolation Techniques Isolation of data in a session is the trickiest part of session management. A session may constitute of multiple requests. ... By Madhura Oak Dec 02, 2013](https://blog.e-zest.com/session-state-isolation-techniques/)

[Session Management There are three ways of session management in n-tier applications: By Madhura Oak Nov 27, 2013](https://blog.e-zest.com/session-management/)

[Transaction and Query timeout Performance is one of the non-functional requirements of an application. It defines the acceptable maximum response time for ... By Madhura Oak Nov 25, 2013](https://blog.e-zest.com/transaction-and-query-timeout/)

[![Multiple Inheritance in Domain Model Design](https://blog.e-zest.com/hs-fs/file-3586010320-png/blog-files/uml-class-diagram-%E2%80%93-bridge-pattern.png) Multiple Inheritance in Domain Model Design While using multiple inheritance in domain model design you need to be cautious as programming languages such as Java do not ... By Madhura Oak Nov 13, 2013](https://blog.e-zest.com/multiple-inheritance-in-domain-model-design/)

## Helping Organizations Thrive in the Digital Age

[Contact Us](https://www.e-zest.com/contact-us)

- [About](https://www.e-zest.com/about-us)
- [Services](https://www.e-zest.com/our-services)
- [Work](https://www.e-zest.com/our-work)
- [Insights](https://blog.e-zest.com/)
- [Healthcare](https://healthcare.e-zest.com/)
- [Accion Labs](https://www.accionlabs.com/)

- <https://www.linkedin.com/company/e-zest-solutions/>
- <https://twitter.com/ezest>
- <https://www.facebook.com/eZest/>
- <https://www.instagram.com/ezestsolutions/>
- <https://www.youtube.com/user/ezestcorporate>

- Dallas
- Detroit
- Hannover
- Vienna
- London
- Pune

 © 2025 e-Zest Solutions

- [Privacy Policy](https://www.e-zest.com/privacypolicy)
- [Cookie Policy](https://www.e-zest.com/cookie-policy)

 Contact us

 Contact us

e-Zest is a leading digital innovation partner for enterprises and technology companies that utilizes emerging technologies for creating engaging customers experiences. Being a customer-focused and technology-driven company, it always helps clients in crafting holistic business value for their software development efforts. It offers software development and consulting services for cloud computing, enterprise mobility, big data and analytics, user experience and digital commerce.