Java Concurrency - Atomic Variable Access

Java Conceptuel Diagram

About

Data Concurrency - Atomic Variable Access in java

Data Type

Primitive

The reads and writes operations are atomic for

Some of the classes in the java.util.concurrent package provide atomic methods that do not rely on synchronization.

Class

The java.util.concurrent.atomic package defines classes that support atomic operations on single variables in a lock-free thread-safe way

Example with an AtomicInteger, the method does not need any synchronization

import java.util.concurrent.atomic.AtomicInteger;

class AtomicCounter {

    private AtomicInteger c = new AtomicInteger(0);

    public void increment() {
        c.incrementAndGet();
    }

    public void decrement() {
        c.decrementAndGet();
    }

    public int value() {
        return c.get();
    }

}

versus the old way with synchronized method

class SynchronizedCounter {
    private int c = 0;

    public synchronized void increment() {
        c++;
    }

    public synchronized void decrement() {
        c--;
    }

    public synchronized int value() {
        return c;
    }

}

Documentation / Reference





Discover More
Java Conceptuel Diagram
Java Concurrency - Synchronization (Thread Safety)

in java. Java offers two basic synchronization idioms: synchronized methods synchronized statements final fields, which cannot be modified after the object is constructed, can be safely read...
Java Conceptuel Diagram
Java Concurrency - java.util.concurrent

Since Java 1.5, java/util/concurrent/package-summaryjava.util.concurrent java.util.concurrent.locks. Interfaces and classes providing a framework for locking and waiting for conditions that is distinct...



Share this page:
Follow us:
Task Runner