Java - using AtomicInteger vs Static int

2019-04-18 13:47发布

问题:

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?

回答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.



回答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();
        }
      }
    }
  }


回答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.



回答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.



回答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



回答6:

I think there is no gurantee to see on count++ the newest value. count++ must read the value of count. Another Thread can have written a new value to count but stored it's value on the Thread local cache, i. e. does not flush to main memory. Also your Thread, that reads count, has no gurantee to read from the main memory, i. e. refresh from main memory. synchronize gurantees that.



回答7:

AtomicInteger is to make the get and increment as an atomic process. It can be thought as a Sequencer in Database. It provides utility methods to increment, decrement delta int values.

static int can cause issue if you are getting counter and then processing and then updating it. AtomicInteger does it easily but you can't use it if you have to update the counter based on processing results.



标签: java atomic