Qubit Atomic
User-friendly atomic operations wrapper providing JDK-like atomic API for Rust.
Overview
Qubit Atomic is a comprehensive atomic operations library that provides easy-to-use atomic types with reasonable default memory orderings, similar to Java's java.util.concurrent.atomic package. It hides the complexity of memory ordering while maintaining zero-cost abstraction and allowing advanced users to access underlying types for fine-grained control.
Design Goals
- Ease of Use: Hides memory ordering complexity with reasonable defaults
- Completeness: Provides high-level operations similar to JDK atomic classes
- Safety: Guarantees memory safety and thread safety
- Performance: Zero-cost abstraction with no additional overhead
- Flexibility: Exposes underlying types via
inner()for advanced users - Simplicity: Minimal API surface without
_with_orderingvariants
Features
🔢 Generic Atomic Primitive Types
- Integer Specializations:
Atomic<i8>,Atomic<u8>,Atomic<i16>,Atomic<u16>,Atomic<i32>,Atomic<u32>,Atomic<i64>,Atomic<u64>,Atomic<i128>,Atomic<u128>,Atomic<isize>,Atomic<usize> - Boolean Specialization:
Atomic<bool>with set, clear, negate, logical AND/OR/XOR, and conditional CAS helpers - Floating-Point Specializations:
Atomic<f32>andAtomic<f64>with arithmetic operations implemented through CAS loops - Rich Operations: increment, decrement, add, subtract, multiply, divide, bitwise operations, max/min
- Functional Updates:
fetch_update,try_update,fetch_accumulate
🔢 AtomicCount and AtomicSignedCount
AtomicCount: non-negative count for active tasks, in-flight requests, and resource usageAtomicSignedCount: signed count for deltas, balances, backlog, and offsets- No-Wrap Semantics: checked updates that panic or return
Noneinstead of wrapping - Zero-Transition Logic:
inc,dec,add, andsubreturn the new value
🔗 Atomic Reference Type
- AtomicRef: Thread-safe atomic reference using
Arc<T> - Reference Updates: Atomic swap and CAS operations
- Guarded Loads:
load_guard()for short-lived reads without cloning on the fast path - Functional Updates: Transform references atomically with
fetch_updateor conditionally withtry_update
🤝 Shared-Owner Convenience Wrappers
ArcAtomic<T>: convenience newtype aroundArc<Atomic<T>>ArcAtomicRef<T>: convenience newtype aroundArc<AtomicRef<T>>ArcAtomicCount/ArcAtomicSignedCount: shared-owner wrappers for the count types- Shared Container Clone: cloning an
ArcAtomic*value shares the same atomic container
🎯 Focused Public API
- Atomic: Generic entry point for primitive atomic values
- AtomicRef: Atomic
Arc<T>reference wrapper AtomicCount/AtomicSignedCount: checked state-oriented semantics (no silent wrap)ArcAtomic*wrappers: ergonomic shared ownership without spellingArc<...>at every use site
Installation
Add this to your Cargo.toml:
[]
= "0.10.2"
Quick Start
Specifying the value type T
Atomic<T> is generic over the primitive value type. Rust usually infers T from the argument to Atomic::new, but literals such as 0 can be ambiguous across integer widths.
In those cases, pick T explicitly using a turbofish on the constructor, or by annotating the variable:
use Atomic;
let wide: = new;
assert_eq!;
let narrow = new;
assert_eq!;
Example: concurrent Atomic<i32>
use Atomic;
use Arc;
use thread;
AtomicCount and AtomicSignedCount
Use Atomic<T> for pure metrics. Use AtomicCount when the
count is part of concurrent state, such as active work or termination checks.
use ;
Shared-owner wrappers
Use the ArcAtomic* wrappers when the atomic container itself is shared across
threads or components. Their clone() operation clones the outer Arc, so all
clones observe and update the same container.
use ;
use Arc;
use thread;
CAS Loop
use Atomic;
Functional Updates
use Atomic;
Atomic Reference
use AtomicRef;
use Arc;
Boolean Flag
use Atomic;
use Arc;
Floating-Point Atomics
use Atomic;
use Arc;
use thread;
API Reference
Common Operations (All Types)
| Method | Description | Memory Ordering |
|---|---|---|
new(value) |
Create new atomic | - |
load() |
Load current value | Acquire |
store(value) |
Store new value | Release |
swap(value) |
Swap value, return old | AcqRel |
compare_set(current, new) |
CAS operation, return Result | AcqRel/Acquire |
compare_set_weak(current, new) |
Weak CAS, return Result | AcqRel/Acquire |
compare_and_exchange(current, new) |
CAS operation, return actual value | AcqRel/Acquire |
compare_and_exchange_weak(current, new) |
Weak CAS, return actual value | AcqRel/Acquire |
fetch_update(f) |
Functional update, return old | AcqRel/Acquire |
try_update(f) |
Conditional functional update, return Option<old> |
AcqRel/Acquire |
inner() |
Access underlying backend type | - |
Integer Operations
| Method | Description | Memory Ordering |
|---|---|---|
fetch_inc() |
Post-increment, return old | Relaxed |
fetch_dec() |
Post-decrement, return old | Relaxed |
fetch_add(delta) |
Post-add, return old | Relaxed |
fetch_sub(delta) |
Post-subtract, return old | Relaxed |
fetch_mul(factor) |
Post-multiply, return old | AcqRel (CAS loop) |
fetch_div(divisor) |
Post-divide, return old | AcqRel (CAS loop) |
fetch_and(value) |
Bitwise AND, return old | AcqRel |
fetch_or(value) |
Bitwise OR, return old | AcqRel |
fetch_xor(value) |
Bitwise XOR, return old | AcqRel |
fetch_not() |
Bitwise NOT, return old | AcqRel |
fetch_max(value) |
Atomic max, return old | AcqRel |
fetch_min(value) |
Atomic min, return old | AcqRel |
fetch_update(f) |
Functional update, return old | AcqRel/Acquire |
try_update(f) |
Conditional functional update, return Option<old> |
AcqRel/Acquire |
fetch_accumulate(x, f) |
Accumulate, return old | AcqRel/Acquire |
Primitive integer operations intentionally use wrapping arithmetic on overflow
and underflow, matching Rust atomic integer semantics. Use AtomicCount or
AtomicSignedCount when overflow or underflow should be rejected.
AtomicCount / AtomicSignedCount operations
| Method | AtomicCount |
AtomicSignedCount |
Memory Ordering | Description |
|---|---|---|---|---|
new(value) |
usize |
isize |
- | Create a count |
zero() |
Yes | Yes | - | Create a zero value |
get() |
usize |
isize |
Acquire | Read the current value |
is_zero() |
Yes | Yes | Acquire | Check whether the value is zero |
is_positive() |
Yes | Yes | Acquire | Check whether the value is positive |
is_negative() |
No | Yes | Acquire | Check whether the value is negative |
inc() |
Yes | Yes | AcqRel/Acquire | Increment by one, return new value |
dec() |
Panic on underflow | Allows negative values | AcqRel/Acquire | Decrement by one, return new value |
add(delta) |
Panic on overflow | Panic on overflow/underflow | AcqRel/Acquire | Add delta, return new value |
sub(delta) |
Panic on underflow | Panic on overflow/underflow | AcqRel/Acquire | Subtract delta, return new value |
try_add(delta) |
None on overflow |
None on overflow/underflow |
AcqRel/Acquire | Checked add |
try_dec() |
None at zero |
No | AcqRel/Acquire (AtomicCount only) |
Checked decrement |
try_sub(delta) |
None on underflow |
None on overflow/underflow |
AcqRel/Acquire | Checked subtract |
Shared-owner wrapper operations
The ArcAtomic* wrappers dereference to their underlying atomic container, so
you can call operations such as load, fetch_inc, store, inc, and sub
directly on the wrapper.
| Method | Available On | Description |
|---|---|---|
new(value) |
ArcAtomic<T>, ArcAtomicCount, ArcAtomicSignedCount |
Create a new shared wrapper from an initial value |
new(Arc<T>) |
ArcAtomicRef<T> |
Create a shared atomic reference from an existing Arc<T> |
from_value(value) |
ArcAtomicRef<T> |
Create a shared atomic reference from an owned value |
from_atomic(...) |
ArcAtomic<T> |
Wrap an existing Atomic<T> |
from_atomic_ref(...) |
ArcAtomicRef<T> |
Wrap an existing AtomicRef<T> |
from_count(...) |
ArcAtomicCount, ArcAtomicSignedCount |
Wrap an existing count container |
from_arc(arc) |
All ArcAtomic* wrappers |
Wrap an existing Arc<...> container |
as_arc() |
All ArcAtomic* wrappers |
Borrow the underlying Arc<...> |
into_arc() |
All ArcAtomic* wrappers |
Consume the wrapper and return the underlying Arc<...> |
strong_count() |
All ArcAtomic* wrappers |
Return the number of strong Arc owners |
Boolean Operations
| Method | Description | Memory Ordering |
|---|---|---|
fetch_set() |
Set to true, return old | AcqRel |
fetch_clear() |
Set to false, return old | AcqRel |
fetch_not() |
Negate, return old | AcqRel |
fetch_and(value) |
Logical AND, return old | AcqRel |
fetch_or(value) |
Logical OR, return old | AcqRel |
fetch_xor(value) |
Logical XOR, return old | AcqRel |
set_if_false(new) |
CAS if false | AcqRel/Acquire |
set_if_true(new) |
CAS if true | AcqRel/Acquire |
Floating-Point Operations
| Method | Description | Memory Ordering |
|---|---|---|
fetch_add(delta) |
Atomic add, return old | AcqRel (CAS loop) |
fetch_sub(delta) |
Atomic subtract, return old | AcqRel (CAS loop) |
fetch_mul(factor) |
Atomic multiply, return old | AcqRel (CAS loop) |
fetch_div(divisor) |
Atomic divide, return old | AcqRel (CAS loop) |
fetch_update(f) |
Functional update, return old | AcqRel/Acquire |
try_update(f) |
Conditional functional update, return Option<old> |
AcqRel/Acquire |
Floating-point CAS operations (compare_set, compare_and_exchange, and weak
variants) compare raw to_bits() representations, not PartialEq. Values such
as 0.0 and -0.0 compare equal but do not CAS-match, and NaN payload bits
must match exactly. Use compare_set when you need an explicit success result,
or compare to_bits() values yourself.
Memory Ordering Strategy
| Operation Type | Default Ordering | Reason |
|---|---|---|
Pure Read (load()) |
Acquire |
Ensure reading latest value |
Pure Write (store()) |
Release |
Ensure write visibility |
Read-Modify-Write (swap(), CAS) |
AcqRel |
Ensure both read and write correctness |
Atomic<T> counter arithmetic (fetch_inc(), fetch_dec(), fetch_add(), fetch_sub()) |
Relaxed |
Pure metrics; no need to sync other data |
CAS-based arithmetic and updates (fetch_mul(), fetch_div(), fetch_update(), try_update(), fetch_accumulate()) |
AcqRel / Acquire |
CAS loop standard semantics |
AtomicCount / AtomicSignedCount (inc(), dec()) |
CAS loop | Values used as concurrent state signals |
Bitwise Operations (fetch_and(), fetch_or()) |
AcqRel |
Usually used for flag synchronization |
Max/Min Operations (fetch_max(), fetch_min()) |
AcqRel |
Often used with threshold checks |
Advanced Usage: Direct Access to Underlying Types
For scenarios requiring fine-grained memory ordering control (approximately 1% of use cases), use inner() to access the underlying backend type:
use Ordering;
use Atomic;
let atomic = new;
// 99% of scenarios: use simple API
let value = atomic.load;
// 1% of scenarios: need fine-grained control
let value = atomic.inner.load;
atomic.inner.store;
Comparison with JDK
| Feature | JDK | Qubit Atomic | Notes |
|---|---|---|---|
| Basic Types | 3 types | Atomic<T> specializations |
Rust supports more integer, floating-point, boolean, and counter use cases |
| Memory Ordering | Implicit (volatile) | Default + inner() optional |
Rust more flexible |
| Weak CAS | weakCompareAndSet |
compare_set_weak |
Equivalent |
| Reference Type | AtomicReference<V> |
AtomicRef<T> |
Rust uses Arc<T> |
AtomicCount / AtomicSignedCount |
Manual composition | AtomicCount, AtomicSignedCount |
Non-negative / signed counts for state tracking |
| Shared Ownership | Usually object references | ArcAtomic<T>, ArcAtomicRef<T>, ArcAtomicCount, ArcAtomicSignedCount |
Convenience wrappers for shared atomic containers |
| Nullability | Allows null |
Use Option<Arc<T>> |
Rust no null pointers |
| Bitwise Operations | Partial support | Full support | Rust more powerful |
| Max/Min Operations | Java 9+ support | Supported | Equivalent |
| API Count | ~20 methods/type | ~25 methods/type | Rust provides more convenience methods |
Performance Considerations
Zero-Cost Abstraction
Primitive wrappers use #[repr(transparent)] and #[inline] so the generic API compiles down to the backend atomic operations:
// Our wrapper
let atomic = new;
let value = atomic.load;
// Compiles to the same code as
let atomic = new;
let value = atomic.load;
When to Use inner()
99% of scenarios: Use default API, which already provides optimal performance.
1% of scenarios: Use inner() only when:
- Extreme performance optimization (need
Relaxedordering) - Complex lock-free algorithms (need precise memory ordering control)
- Interoperating with code that directly uses standard library or
portable-atomicbackend types
Golden Rule: Default API first, inner() as last resort.
Testing & Code Coverage
This project maintains comprehensive test coverage with detailed validation of all functionality.
Running Tests
# Run all tests
# Run benchmarks
# List benchmark scenarios
# Run with coverage report
# Generate text format report
# Run CI checks (format, clippy, test, coverage)
Coverage Metrics
See COVERAGE.md for detailed coverage statistics.
Dependencies
Runtime dependencies are intentionally small:
arc-swappowersAtomicRef<T>.portable-atomicprovides the stable backend forAtomic<i128>andAtomic<u128>.
License
Copyright (c) 2025 - 2026. Haixing Hu, Qubit Co. Ltd. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
See LICENSE for the full license text.
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
Development Guidelines
- Follow the Rust API guidelines
- Maintain comprehensive test coverage
- Document all public APIs with examples
- Ensure all tests pass before submitting PR
Author
Haixing Hu - Qubit Co. Ltd.
Related Projects
More Rust libraries from Qubit are published under the qubit-ltd organization on GitHub.
Repository: https://github.com/qubit-ltd/rs-atomic