Atomically do bitwise OR between the value in the AtomicInteger and the specified value - Java java.util.concurrent.atomic

Java examples for java.util.concurrent.atomic:AtomicInteger

Description

Atomically do bitwise OR between the value in the AtomicInteger and the specified value

Demo Code


//package com.java2s;
import java.util.concurrent.atomic.AtomicInteger;

public class Main {
    /**//from w  w  w. j  a  v  a  2 s . c  o  m
     * Atomically do bitwise OR between the value in the AtomicInteger and the toOrValue, and set the new value to the
     * AtomicInteger and also return the new value.
     *
     * @param ai the atomic variable to operate on
     * @param toOrValue the value to do the OR operation
     * @return the new value.
     * */
    public static int bitwiseOrAndGet(final AtomicInteger ai,
            final int toOrValue) {
        int oldValue = ai.get();
        int newValue = oldValue | toOrValue;
        while (oldValue != newValue
                && !ai.compareAndSet(oldValue, newValue)) {
            oldValue = ai.get();
            newValue = oldValue | toOrValue;
        }
        return newValue;
    }
}

Related Tutorials