Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - using AtomicInteger vs Static int

Tags:

java

atomic

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?

like image 403
user547453 Avatar asked Nov 28 '12 05:11

user547453


People also ask

Should I use AtomicInteger?

Conclusion. As discussed above, the primary use of AtomicInteger is when we are in multi-threaded context and we need to perform atomic operations on an int value without using synchronized keyword. Using the AtomicInteger is equally faster and more readable than performing the same using synchronization.

What is difference between Integer and AtomicInteger?

Integers are object representations of literals and are therefore immutable, you can basically only read them. AtomicIntegers are containers for those values. You can read and set them. Same as asigning a value to variable.

Why do we use AtomicInteger in Java?

An AtomicInteger is used in applications such as atomically incremented counters, and cannot be used as a replacement for an Integer . However, this class does extend Number to allow uniform access by tools and utilities that deal with numerically-based classes.

Is AtomicInteger set thread-safe?

7. Atomic Objects. It's also possible to achieve thread-safety using the set of atomic classes that Java provides, including AtomicInteger, AtomicLong, AtomicBoolean and AtomicReference. Atomic classes allow us to perform atomic operations, which are thread-safe, without using synchronization.


1 Answers

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

like image 154
Kumar Vivek Mitra Avatar answered Oct 17 '22 00:10

Kumar Vivek Mitra