Java原子性一个好的“比较和交换"框架?

编程入门 行业动态 更新时间:2024-10-28 08:22:21
本文介绍了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.

推荐答案

我只会使用 java.util.concurrent.AtomicReference ,除非您真的需要完整的相等性检查,而不是简单的==.

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原子性一个好的“比较和交换"框架?

本文发布于:2023-11-25 08:11:03,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1628976.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:原子   框架   Java   quot

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!