Java Atomicity & a good Compare and Swap framework

2019-07-29 07:00发布

问题:

Do you guys think this is a good generic framework for atomic operations? Also do you think its correct to say With respect to Java applicatitions individual byte codes are atomic as there is no way of executing more than one byte code at a time with a single JVM? So if there was a single byte code for if else, then this if else instruction would be atomic?

// CAS, Compare and Swap
public abstract class CASOperation<T> {

protected T valueAtStart;

public CASOperation(){
    valueAtStart = objectToReview();
}

public void exec(){
    synchronized(this){
        while(!valueAtStartEqualsTheCurrent()){
            valueAtStart = objectToReview();
        }
        execImp();
    }
}

private boolean valueAtStartEqualsTheCurrent() {
    if (objectToReview().equals(valueAtStart)){
        return true;
    } else {
        return false;
    }
}

abstract protected T objectToReview();

abstract protected void execImp();

Its meant to be a compare and execute framework really, so after checking that the original snapped value hasn't changed then we execute some block of code.

回答1:

I would just use java.util.concurrent.AtomicReference unless you really need the full equality check instead of a simple ==.

compareAndSet returns a value saying whether or not the value was the expected one, so you can then conditionally execute other code.

Executing the abstract method in a synchronized block sounds like a potentially risky business - there's no indication or constraint of how long that could take.

Put it this way: I think that unless I knew of a specific requirement to use something like your proposed framework, I'd stick with the types in java.util.concurrent.atomic.



回答2:

Do you guys think this is a good generic framework for atomic operations?

Yes, it's in the java.util.concurrent.atomic package.

if there was a single byte code for "if else", then this "if else" instruction would be atomic?

Not necessarily - one bytecode instruction might translate into more than one machine instruction.

Note: your code uses a synchronized block which is never released within one call - so if the condition is false when entering the block, it might never become true.