Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!
  • Java

Idiom #33 Atomically read and update variable

Assign to the variable x the new value f(x), making sure that no other thread may modify x between the read and the write.

class Example<T> {
    T x;
    Object lock = new Object();
    T read() {
        synchronized (lock) {
            return x;
        }
    }
    void write(T x) {
        synchronized (lock) {
            this.x = x;
        }
    }
}

"Synchronized" access.
volatile T x;

"Atomic" access.
synchronized(lock){
  x = f(x);
}

With this idiom, you have to manually ensure that any thread modifying x is guarded by the same lock object.
(def x (atom 0))
(def f inc)
(swap! x f)

New implementation...
< >
programming-idioms.org