Atomically do bitwise AND 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 AND between the value in the AtomicInteger and the specified Value

Demo Code


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

public class Main {
    /**//  ww  w  .  jav a2s  .c o  m
     * Atomically do bitwise AND between the value in the AtomicInteger and the toAndValue, and set the new value to the
     * AtomicInteger and also return the new value.
     *
     * @param ai the atomic variable to operate on
     * @param toAndValue the value to do the OR operation
     * @return the new value.
     * */
    public static int bitwiseAndAndGet(final AtomicInteger ai,
            final int toAndValue) {
        int oldValue = ai.get();
        int newValue = oldValue & toAndValue;
        while (oldValue != newValue
                && !ai.compareAndSet(oldValue, newValue)) {
            oldValue = ai.get();
            newValue = oldValue & toAndValue;
        }
        return newValue;
    }
}

Related Tutorials