Java原子性一个好的“比较和交换"框架? [英] Java Atomicity & a good Compare and Swap framework?

查看:85
本文介绍了Java原子性一个好的“比较和交换"框架?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你们认为这是原子操作的良好通用框架吗? 您还认为说正确吗?关于Java应用程序,单个字节代码是原子的,因为无法使用单个JVM一次执行一个以上的字节代码?因此,如果if仅有一个字节代码,那么if else指令将是原子的吗?

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.

推荐答案

我只会使用

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.

这样写:我认为除非我知道特定的要求使用类似您提议的框架的东西,否则我会坚持使用java.util.concurrent.atomic中的类型.

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.

这篇关于Java原子性一个好的“比较和交换"框架?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆