Is it possible to implement own AtomicInteger on Java? (jdk.internal.misc.Unsafe)

Viewed 98

Is it possible to implement my own AtomicInteger in Java?

What I see under the hood of methods:

public final int addAndGet(int delta) {
    for (;;) {
        int current = get();
        int next = current + delta;         // Only difference
        if (compareAndSet(current, next))
            return next;
    }
}

public final int incrementAndGet() {
    for (;;) {
        int current = get();
        int next = current + 1;             // Only difference
        if (compareAndSet(current, next))
            return next;
    }
}

So anyway need to use compareAndSet. Which is:

public final boolean compareAndSet(int expectedValue, int newValue) {
        return U.compareAndSetInt(this, VALUE, expectedValue, newValue);
    }

where private static final jdk.internal.misc.Unsafe U = jdk.internal.misc.Unsafe.getUnsafe();

So all atomics use Unsafe ( which I don't know well and highly doubt if one need it at job) which I guess use low-level/cpu instructions

Compare and Swap

My question is: is it possible to write atomics on java, or anyway need to call Unsafe and end up with it?

0 Answers
Related