Java - using AtomicInteger vs Static int

16,284

Solution 1

- AtomicInteger is used to perform the atomic operation over an integer, its an alternative when you don't want to use synchronized keyword.

- Using a volatile on a Non-Atomic field will give inconsistent result.

int volatile count;

public void inc(){

count++

}

- static will make a variable shared by all the instances of that class, But still it will produce an inconsistent result in multi-threading environment.

So try these when you are in multithreading environment:

1. Its always better to follow the Brian's Rule:

When ever we write a variable which is next to be read by another thread, or when we are reading a variable which is written just by another thread, it needs to be synchronized. The shared fields must be made private, making the read and write methods/atomic statements synchronized.

2. Second option is using the Atomic Classes, like AtomicInteger, AtomicLong, AtomicReference, etc.

Solution 2

I agree with @Kumar's answer.

Volatile is not sufficient - it has some implications for the memory order, but does not ensure atomicity of ++.

The really difficult thing about multi-threaded programming is that problems may not show up in any reasonable amount of testing. I wrote a program to demonstrate the issue, but it has threads that do nothing but increment counters. Even so, the counts are within about 1% of the right answer. In a real program, in which the threads have other work to do, there may be a very low probability of two threads doing the ++ close enough to simultaneously to show the problem. Multi-thread correctness cannot be tested in, it has to be designed in.

This program does the same counting task using a simple static int, a volatile int, and an AtomicInteger. Only the AtomicInteger consistently gets the right answer. A typical output on a multiprocessor with 4 dual-threaded cores is:

count: 1981788 volatileCount: 1982139 atomicCount: 2000000 Expected count: 2000000

Here's the source code:

  import java.util.ArrayList;
  import java.util.List;
  import java.util.concurrent.atomic.AtomicInteger;

  public class Test {
    private static int COUNTS_PER_THREAD = 1000000;
    private static int THREADS = 2;

    private static int count = 0;
    private static volatile int volatileCount = 0;
    private static AtomicInteger atomicCount = new AtomicInteger();

    public static void main(String[] args) throws InterruptedException {
      List<Thread> threads = new ArrayList<Thread>(THREADS);
      for (int i = 0; i < THREADS; i++) {
        threads.add(new Thread(new Counter()));
      }
      for (Thread t : threads) {
        t.start();
      }
      for (Thread t : threads) {
        t.join();
      }
      System.out.println("count: " + count +  " volatileCount: " + volatileCount + " atomicCount: "
          + atomicCount + " Expected count: "
          + (THREADS * COUNTS_PER_THREAD));
    }

    private static class Counter implements Runnable {
      @Override
      public void run() {
        for (int i = 0; i < COUNTS_PER_THREAD; i++) {
          count++;
          volatileCount++;
          atomicCount.incrementAndGet();
        }
      }
    }
  }

Solution 3

With AtomicInteger the incrementAndGet() guaranteed to be atomic.
If you use count++ to get the previous value it is not guaranteed to be atomic.


Something the I missed from your question - and was stated by other answer - static has nothing to do with threading.

Solution 4

"static" make the var to be class level. That means, if you define "static int count" in a class, no matter how many instances you created of the class, all instances use same "count". While AtomicInteger is a normal class, it just add synchronization protection.

Solution 5

static int counter would give you inconsistent result in multithreaded environment unless you make the counter volatile or make the increment block synchronized.

In case of automic it gives lock-free thread-safe programming on single variables.

More detail in automic's and link

Share:
16,284

Related videos on Youtube

user547453
Author by

user547453

Updated on October 09, 2022

Comments

  • user547453
    user547453 over 1 year

    While using multiple threads I have learnt to use Static variables whenever I want to use a counter that will be accessed by multiple threads.

    Example:

    static int count=0; Then later in the program I use it as count++;.

    Today I came across something called AtomicInteger and I also learned that it is Thread safe and could use one of its methods called getAndInrement() to achieve the same effect.

    Could anyone help me to understand about using static atomicInteger versus static int count?

    • Bhesh Gurung
      Bhesh Gurung over 11 years
      static doesn't have anything to do with multi-threading.
  • Itay Karo
    Itay Karo over 11 years
    it means, for example, that if two threads are using, for example prevCount = count++ on the same time, it might be that both of the thread will get the same value of prevCount.
  • Patricia Shanahan
    Patricia Shanahan over 11 years
    I don't think volatile is enough to make ++ safe.