chopper draw lion4
chopper draw lion4

Reputation: 13507

Java: What is an atomic number?

I started going through Spring tutorial and it has me initialize an atomic number. I wasn't sure what an atomic number was, so I googled around and could not find a straight forward answer. What is an atomic number in Java?

Upvotes: 2

Views: 2127

Answers (3)

MAD
MAD

Reputation: 175

Reference: Java Atomic Variables

Traditional multi-threading approaches use locks to protect shared resources. Synchronization objects like Semaphores provide mechanisms for the programmer to write code that doesn't modify a shared resource concurrently. The synchronization approaches block other threads when one of the thread is modifying a shared resource. Obviously blocked threads are not doing meaningful work waiting for the lock to be released.

Atomic operations on the contrast are based on non-blocking algorithms in which threads waiting for shared resources don't get postponed. Atomic operations are implemented using hardware primitives like compare and swap (CAS) which are atomic instructions used in multi-threading for synchronization.

Java supports atomic classes that support lock free, thread safe programming on single variables. These classes are defined in java.util.concurrent.atomic package. Some of the key classes include AtomicBoolean, AtomicInteger, AtomicLong, AtomicIntegerArray, AtomicLongArray and AtomicReference.

Upvotes: 0

Enno Shioji
Enno Shioji

Reputation: 26882

If more than one thread executes a code like this, the counter can end up fewer than it should be.

int count
void increment() {
    int previous = count;
    count = previous + 1;
}

This is because it takes two steps to increment the counter, and a thread can read the count before another thread can store the new value (note that re-writing this into a one-liner doesn't change this fact; the JVM has to perform two steps regardless of how you write it). Forcing multiple steps to always happen in one unit (e.g. the read of the count and storing of the new count) is called "making the operation atomic".

"Atomic" values are objects that wrap values and exposes methods that conveniently provide common atomic operations, such as AtomicInteger#increment().

Upvotes: 2

ovdsrn
ovdsrn

Reputation: 793

Atomic means that the update operations done on that type are ensured to be done atomically (in one step, in one goal). Atomic types are valuable to use in a concurrent context (as "better volatiles")

Upvotes: 3

Related Questions