![]() |
VOOZH | about |
Atomic is a type of variable that performs read, write and update in a single uninterruptible step, ensuring thread-safe operations and preventing race conditions
Example: AtomicInteger in Multi-threading
200000000
Explanation:
Example: Without Atomic Variables (Unsafe Code)
100238993
Explanation:
Below are some commonly used atomic variable types in Java.
AtomicInteger provides atomic operations (increment, decrement, add, etc.) on integer values without synchronization.
Final Value: 9
AtomicLong supports atomic operations on long values for thread-safe numeric computations.
Updated Value: 150
AtomicBoolean represents a boolean value that can be atomically updated for safe flag-based operations.
Operation performed only once!
AtomicReference allows atomic read and write of object references, useful for non-primitive data.
Current Message: Hi, from AtomicReference!
AtomicIntegerArray enables atomic operations on elements of an integer array for thread-safe updates.
Array after update: [1, 3, 3] Value at index 1: 3
| Method | Description |
|---|---|
| get() | Returns the current value. |
| set(value) | Sets the value to the given value. |
| getAndSet(value) | Atomically sets a new value and returns the old one. |
| incrementAndGet() | Increments the value by one and returns the updated value. |
| getAndIncrement() | Increments the value by one and returns the previous value. |
| decrementAndGet() | Decrements the value by one and returns the updated value. |
| addAndGet(delta) | Adds the specified value and returns the updated result. |
| getAndAdd(delta) | Adds the specified value and returns the previous result. |
| compareAndSet(expected, update) | Atomically updates the value only if it equals the expected value. |
| lazySet(value) | Eventually sets the value (may be delayed for performance). |