说说你对Jdk并发包中的CAS实现的了解?

    在jdk中通过内部提供的Unsafe实现的CAS操作,在这个类的实现中提供了对并发的支持,比如compareAndSwap方法的实现就是原子性的,并且可用来提供高性能、无锁的数据结构。CAS的操作的语义是(compare and set),即比较原值(old)是否和期望(expect)的值相同,如果相同则将该值(old)设置成新值(new)。jdk中的cocurrent包中的atomic、lock、AQS等都是基于该api实现的。

 

参考资料:

Java并发编程之CAS

使用Java5+提供的CAS特性而不是使用自己实现的的好处是Java5+中内置的CAS特性可以让你利用底层的你的程序所运行机器的CPU的CAS特性。这会使还有CAS的代码运行更快。

聊聊并发(二)Java SE1.6中的Synchronized

2 术语定义

术语英文说明
CASCompare and Swap比较并设置。用于在硬件层面上提供原子性操作。在 Intel 处理器中,比较并交换通过指令cmpxchg实现。比较是否和给定的数值一致,如果一致则修改,不一致则不修改。

Java Magic. Part 4: sun.misc.Unsafe

在使用Unsafe之前,我们需要创建Unsafe对象的实例。这并不像Unsafe unsafe = new Unsafe()这么简单,因为Unsafe的构造器是私有的。它也有一个静态的getUnsafe()方法,但如果你直接调用Unsafe.getUnsafe(),你可能会得到SecurityException异常。只能从受信任的代码中使用这个方法。

Field f = Unsafe.class.getDeclaredField("theUnsafe");
f.setAccessible(true);
Unsafe unsafe = (Unsafe) f.get(null);

 JEP 193: Variable Handles

Motivation

As concurrent and parallel programming in Java continue to expand, programmers are increasingly frustrated by not being able to use Java constructs to arrange atomic or ordered operations on the fields of individual classes; for example, atomically incrementing a count field. Until now the only ways to achieve these effects were to use a stand-alone AtomicInteger (adding both space overhead and additional concurrency issues to manage indirection) or, in some situations, to use atomic FieldUpdaters (often encountering more overhead than the operation itself), or to use the unsafe (and unportable and unsupported) sun.misc.UnsafeAPI for JVM intrinsics. Intrinsics are faster, so they have become widely used, to the detriment of safety and portability.

Without this JEP, these problems are expected to become worse as atomic APIs expand to cover additional access-consistency policies (aligned with the recent C++11 memory model) as part of Java Memory Model revisions.

转载于:https://my.oschina.net/u/914290/blog/801039

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值