Java Atomicity & a good Compare and Swap framework?

半世苍凉 提交于 2020-01-06 03:07:15

问题


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.



来源:https://stackoverflow.com/questions/14771174/java-atomicity-a-good-compare-and-swap-framework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!