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?
–
AtomicIntegeris used to perform the atomic operation over an integer, its an alternative when you don’t want to usesynchronizedkeyword.– Using a
volatileon a Non-Atomic field will give inconsistent result.–
staticwill 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:
2. Second option is using the
Atomic Classes, likeAtomicInteger, AtomicLong, AtomicReference, etc.