unset AtomicInteger Bit By Value - Java java.util.concurrent.atomic

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

Description

unset AtomicInteger Bit By Value

Demo Code


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

public class Main {
    /**/*from   www.j  a v a  2 s.  c  o m*/
     * @param ai the AtomicInteger to operate on
     * @param value from the value get the index of the set bit from the least significant bit. Do the operation on that
     *          index.
     * */
    public static void unsetBitByValue(final AtomicInteger ai,
            final int value) {
        unsetBitByIndex(ai, Integer.numberOfTrailingZeros(value));
    }

    /**
     * @param ai the AtomicInteger to operate on
     * @param n the nth bit from the least significant bit to compare
     * */
    public static void unsetBitByIndex(final AtomicInteger ai, final int n) {
        unsetBitIfSetByIndex(ai, n);
    }

    /**
     * @return true if operation is conducted, false if the bit is already unset.
     * @param ai the AtomicInteger to operate on
     * @param n the nth bit from the least significant bit to compare, the least significant bit is 0
     * */
    public static boolean unsetBitIfSetByIndex(final AtomicInteger ai,
            final int n) {
        if (n >= Integer.SIZE) {
            throw new IllegalArgumentException(
                    "Out of int bit index boundary (31)");
        }
        int bitInt = 1 << n;
        int oldValue = ai.get();
        int newValue = oldValue & ~bitInt;
        while (newValue != oldValue
                && !ai.compareAndSet(oldValue, newValue)) {
            oldValue = ai.get();
            newValue = oldValue & ~bitInt;
        }
        return newValue != oldValue;
    }
}

Related Tutorials