# V6074. Non-atomic modification of volatile variable.

The analyzer has detected a non-atomic modification of a 'volatile' variable, which may result in a race condition.

As you know, the use of 'volatile' guarantees that the actual value of the marked variable will be known to each thread. It is also important to mention that the 'volatile' modifier is used to tell the JVM that every assignment to this variable and every read from it must be atomic.

One may assume that marking variables as 'volatile' should be enough to use them safely in a multithreaded application, but what about operations modifying a 'volatile' variable whose future value depends on the current one?

Such operations are as follows:

- var++, ‑‑var, ...
- var += smt, var *= smt, ...
- ...

The following example demonstrates using a 'volatile' variable as a counter (counter++).

    class Counter
    {
      private volatile int counter = 0;
      ....
      public void increment()
      {
        counter++; // counter = counter + 1
      }
      ....
    }

This increment operation looks like a single operation, but in reality it is a sequence of read-modify-write operations. This is where the race condition stems from.

Suppose we have two threads simultaneously handling an object of class Counter and incrementing the 'counter' variable (10):

[counter == 10, temp == 10] Thread N1 reads the value of 'counter' into a temporary variable.

[counter == 10, temp == 11] Thread N1 modifies the temporary variable.

[counter == 10, temp == 10] Thread N2 reads the value of 'counter' into a temporary variable.

[counter == 11, temp == 11] Thread N1 writes the value of the temporary variable into 'counter'.

[counter == 11, temp == 11] Thread N2 modifies the temporary variable.

[counter == 11, temp == 11] Thread N2 writes the value of the temporary variable into 'counter'.

We expected the 'counter' variable to have the resulting value 12 (not 11) since the two threads were incrementing the same variable. The threads could also increment the variable in turn, which is where we would get the expected result. The result of this operation may vary every time it is executed!

To avoid such behavior of atomic operations on shared variables, you can use the following techniques:

- A 'synchronized' block,
- Classes from the java.util.concurrent.atomic package,
- Locks from the java.util.concurrent.locks package

This is one version of how the example above could be fixed:

    class Counter
    {
      private volatile int counter = 0;
      ....
      public synchronized void increment()
      {
        counter++;
      }
      ....
    }

Another version:

    class Counter
    {
      private final AtomicInteger counter = new AtomicInteger(0);
      ....
      public void increment()
      {
        counter.incrementAndGet();
      }
      ....
    }

This diagnostic is classified as:

CWE-567 CERT-VNA02-J

You can look at examples of errors detected by the V6074 diagnostic.