- 浏览: 161838 次
- 性别:
- 来自: 广州
文章分类
最新评论
-
兰斯洛特1987:
顶!!!!谢谢分享.最近我也在研究这玩意...
Java语言的Hook实现 -
pu02203:
我把Confidant.jar, 丢进去eclipse, 里面 ...
重磅推出诛仙辅助软件第二波:Java版按键精灵 -
泣血端午:
Calculagraph 这是哪个类啊?
A星算法 -
haitaohehe:
我使用的是jstl1.0 可是在使用<c:set va ...
JSTL1.0和JSTL1.1的区别 -
micheal19840929:
学习楼主,我也测试一下~看看兼容性吧。lanlanzhilia ...
手机版飞鸽传书:无线牵
J2SE 5.0提供了一组atomic class来帮助我们简化同步处理。基本工作原理是使用了同步synchronized的方法实现了对一个long, integer, 对象的增、减、赋值(更新)操作. 比如对于++运算符AtomicInteger可以将它持有的integer 能够atomic 地递增。在需要访问两个或两个以上 atomic变量的程序代码(或者是对单一的atomic变量执行两个或两个以上的操作)通常都需要被synchronize以便两者的操作能够被当作是一个atomic的单元。
对array atomic变量来说,一次只有一个索引变量可以变动,并没有功能可以对整个array做atomic化的变动。
关于Atomic的几个方法
getAndSet() : 设置新值,返回旧值.
compareAndSet(expectedValue, newValue) : 如果当前值(current value)等于期待的值(expectedValue), 则原子地更新指定值为新值(newValue), 如果更新成功,返回true, 否则返回false, 换句话可以这样说: 将原子变量设置为新的值, 但是如果从我上次看到的这个变量之后到现在被其他线程修改了(和我期望看到的值不符), 那么更新失败
从effective java (2)中拿来的一个关于AtomicReference的一个例子:
Java代码
- public class AtomicTest {
- private int x, y;
- private enum State {
- NEW, INITIALIZING, INITIALIZED
- };
- private final AtomicReference<State> init = new AtomicReference<State>(State.NEW);
- public AtomicTest() {
- }
- public AtomicTest(int x, int y) {
- initialize(x, y);
- }
- private void initialize(int x, int y) {
- if (!init.compareAndSet(State.NEW, State.INITIALIZING)) {
- throw new IllegalStateException("initialize is error");
- }
- this.x = x;
- this.y = y;
- init.set(State.INITIALIZED);
- }
- public int getX() {
- checkInit();
- return x;
- }
- public int getY() {
- checkInit();
- return y;
- }
- private void checkInit() {
- if (init.get() == State.INITIALIZED) {
- throw new IllegalStateException("uninitialized");
- }
- }
- }
- public class AtomicTest {
- private int x, y;
- private enum State {
- NEW, INITIALIZING, INITIALIZED
- };
- private final AtomicReference<State> init = new AtomicReference<State>(State.NEW);
- public AtomicTest() {
- }
- public AtomicTest(int x, int y) {
- initialize(x, y);
- }
- private void initialize(int x, int y) {
- if (!init.compareAndSet(State.NEW, State.INITIALIZING)) {
- throw new IllegalStateException("initialize is error");
- }
- this.x = x;
- this.y = y;
- init.set(State.INITIALIZED);
- }
- public int getX() {
- checkInit();
- return x;
- }
- public int getY() {
- checkInit();
- return y;
- }
- private void checkInit() {
- if (init.get() == State.INITIALIZED) {
- throw new IllegalStateException("uninitialized");
- }
- }
- }
public class AtomicTest { private int x, y; private enum State { NEW, INITIALIZING, INITIALIZED }; private final AtomicReference<State> init = new AtomicReference<State>(State.NEW); public AtomicTest() { } public AtomicTest(int x, int y) { initialize(x, y); } private void initialize(int x, int y) { if (!init.compareAndSet(State.NEW, State.INITIALIZING)) { throw new IllegalStateException("initialize is error"); } this.x = x; this.y = y; init.set(State.INITIALIZED); } public int getX() { checkInit(); return x; } public int getY() { checkInit(); return y; } private void checkInit() { if (init.get() == State.INITIALIZED) { throw new IllegalStateException("uninitialized"); } } } public class AtomicTest { private int x, y; private enum State { NEW, INITIALIZING, INITIALIZED }; private final AtomicReference<State> init = new AtomicReference<State>(State.NEW); public AtomicTest() { } public AtomicTest(int x, int y) { initialize(x, y); } private void initialize(int x, int y) { if (!init.compareAndSet(State.NEW, State.INITIALIZING)) { throw new IllegalStateException("initialize is error"); } this.x = x; this.y = y; init.set(State.INITIALIZED); } public int getX() { checkInit(); return x; } public int getY() { checkInit(); return y; } private void checkInit() { if (init.get() == State.INITIALIZED) { throw new IllegalStateException("uninitialized"); } } }
上面的例子比较容易懂, 不过貌似没什么价值, 而在实际的应用中, 我们一般采用下面的方式来使用atomic class:
Java代码
- public class CounterTest {
- AtomicInteger counter = new AtomicInteger(0);
- public int count() {
- int result;
- boolean flag;
- do {
- result = counter.get();
- // 断点
- // 单线程下, compareAndSet返回永远为true,
- // 多线程下, 在与result进行compare时, counter可能被其他线程set了新值, 这时需要重新再取一遍再比较,
- // 如果还是没有拿到最新的值, 则一直循环下去, 直到拿到最新的那个值
- flag = counter.compareAndSet(result, result + 1);
- } while (!flag);
- return result;
- }
- public static void main(String[] args) {
- final CounterTest c = new CounterTest();
- new Thread() {
- @Override
- public void run() {
- c.count();
- }
- }.start();
- new Thread() {
- @Override
- public void run() {
- c.count();
- }
- }.start();
- new Thread() {
- @Override
- public void run() {
- c.count();
- }
- }.start();
- }
- }
- public class CounterTest {
- AtomicInteger counter = new AtomicInteger(0);
- public int count() {
- int result;
- boolean flag;
- do {
- result = counter.get();
- // 断点
- // 单线程下, compareAndSet返回永远为true,
- // 多线程下, 在与result进行compare时, counter可能被其他线程set了新值, 这时需要重新再取一遍再比较,
- // 如果还是没有拿到最新的值, 则一直循环下去, 直到拿到最新的那个值
- flag = counter.compareAndSet(result, result + 1);
- } while (!flag);
- return result;
- }
- public static void main(String[] args) {
- final CounterTest c = new CounterTest();
- new Thread() {
- @Override
- public void run() {
- c.count();
- }
- }.start();
- new Thread() {
- @Override
- public void run() {
- c.count();
- }
- }.start();
- new Thread() {
- @Override
- public void run() {
- c.count();
- }
- }.start();
- }
- }
public class CounterTest { AtomicInteger counter = new AtomicInteger(0); public int count() { int result; boolean flag; do { result = counter.get(); // 断点 // 单线程下, compareAndSet返回永远为true, // 多线程下, 在与result进行compare时, counter可能被其他线程set了新值, 这时需要重新再取一遍再比较, // 如果还是没有拿到最新的值, 则一直循环下去, 直到拿到最新的那个值 flag = counter.compareAndSet(result, result + 1); } while (!flag); return result; } public static void main(String[] args) { final CounterTest c = new CounterTest(); new Thread() { @Override public void run() { c.count(); } }.start(); new Thread() { @Override public void run() { c.count(); } }.start(); new Thread() { @Override public void run() { c.count(); } }.start(); } } public class CounterTest { AtomicInteger counter = new AtomicInteger(0); public int count() { int result; boolean flag; do { result = counter.get(); // 断点 // 单线程下, compareAndSet返回永远为true, // 多线程下, 在与result进行compare时, counter可能被其他线程set了新值, 这时需要重新再取一遍再比较, // 如果还是没有拿到最新的值, 则一直循环下去, 直到拿到最新的那个值 flag = counter.compareAndSet(result, result + 1); } while (!flag); return result; } public static void main(String[] args) { final CounterTest c = new CounterTest(); new Thread() { @Override public void run() { c.count(); } }.start(); new Thread() { @Override public void run() { c.count(); } }.start(); new Thread() { @Override public void run() { c.count(); } }.start(); } }
类似i++这样的"读-改-写"复合操作(在一个操作序列中, 后一个操作依赖前一次操作的结果), 在多线程并发处理的时候会出现问题, 因为可能一个线程修改了变量, 而另一个线程没有察觉到这样变化, 当使用原子变量之后, 则将一系列的复合操作合并为一个原子操作,从而避免这种问题, i++=>i.incrementAndGet()
原子变量只能保证对一个变量的操作是原子的, 如果有多个原子变量之间存在依赖的复合操作, 也不可能是安全的, 另外一种情况是要将更多的复合操作作为一个原子操作, 则需要使用synchronized将要作为原子操作的语句包围起来. 因为涉及到可变的共享变量(类实例成员变量)才会涉及到同步, 否则不必使用synchronized
发表评论
-
快速开方算法比较
2010-08-18 17:34 1345快速开方算法比较: public class Test { ... -
Java父线程与子线程
2010-06-12 12:49 2717问:在父线程中New了一个子线程,想在停止父线程时也停止子线程 ... -
反射在设计模式中的应用
2010-06-08 10:52 703利用设计模式可以使我 ... -
Reader和InputStream的区别
2010-05-28 13:21 1238Reader支持16位的Unicode字符输出,InputSt ... -
[原创]多线程之队列式执行任务
2010-04-29 10:24 927前言:最近做的一个项目正好要用到多线程,而且要实现 ... -
java内存的思考与总结
2010-02-10 16:13 01. java中堆与栈 在Java程 ... -
关于switch语句
2010-02-10 16:10 783switch语句在一定程度上是有动态跳转(函数指针就是一种动态 ... -
代码优化之-优化除法
2010-02-09 13:57 2419说明:文章中的很多数据可能在新的CPU或不同的CPU或不同的系 ... -
Supported Encodings
2010-02-09 13:41 883The classes java.io.InputStream ... -
应用JAD批量反编译CLASS文件
2010-02-09 12:31 754反编译别人的程序是不对的,但是有时候由于某种原因,不得不反编译 ... -
数组快速复制
2010-02-08 15:33 670data[0] = 0 ; int len = 1 ; i ... -
深刻理解Java编程的7个例子
2010-01-14 10:13 6111. 阅读下列代码回答问 ... -
重磅推出诛仙辅助软件第二波:Java版按键精灵
2009-09-16 18:43 3939前言:上次推出诛仙答题辅助软件用起来不错(想上十名榜不难,YY ... -
Java语言的Hook实现
2009-08-25 17:39 11314引言:最近在玩完美时 ...
相关推荐
2.2.2 原子类(AtomicInteger,AtomicLong,AtomicReference) 13 2.3 线程本地存储(Java.lang.ThreadLocal) 15 2.4 线程阻塞 17 2.4.1 调用sleep(millisecond)使任务进入休眠状态 17 2.4.2 等待输出与输入 17 2.4.3...
1. java.util.concurrent - Java 并发工具包 2. 阻塞队列 BlockingQueue 3. 数组阻塞队列 ArrayBlockingQueue 4. 延迟队列 DelayQueue 5. 链阻塞队列 LinkedBlockingQueue ...25. 原子性引用型 AtomicReference
1. java.util.concurrent - Java 并发工具包 2. 阻塞队列 BlockingQueue 3. 数组阻塞队列 ArrayBlockingQueue 4. 延迟队列 DelayQueue 5. 链阻塞队列 LinkedBlockingQueue ...25. 原子性引用型 AtomicReference
本资源包含两个 pdf 文档,一本根据 Jakob Jenkov 最新博客 (http://tutorials.jenkov.com/java-util-concurrent/index.html) 整理的 java_util_concurrent_user_guide_en.pdf,一...25. 原子性引用型 AtomicReference
数组阻塞队列ArrayBlockingQueue,延迟队列DelayQueue, ...原子性长整型 AtomicLong,原子性引用型 AtomicReference 修改数据: 一 服务端修改数据: 一 文章知识点与官方知识档案匹配,可进一步学习相关知识
本资源包含两个 pdf 文档,一本根据 Jakob Jenkov 最新博客 (http://tutorials.jenkov.com/java-util-concurrent/index.html) 整理的 java_util_concurrent_user_guide_en.pdf,一...25. 原子性引用型 AtomicReference
Java concurrency之AtomicLong原子类_动力节点Java学院整理,动力节点口口相传的Java黄埔军校
主要介绍了Java中对AtomicInteger和int值在多线程下递增操作的测试,本文得出AtomicInteger操作 与 int操作的效率大致相差在50-80倍上下的结论,需要的朋友可以参考下
java_util_concurrent_user_guide_cn.pdf 内容预览: 1. java.util.concurrent - Java 并发工具包 2. 阻塞队列 ... 原子性整型 AtomicInteger 24. 原子性长整型 AtomicLong 25. 原子性引用型 AtomicReferenc
AtomicInteger, AtomicLong, AtomicBoolean, AtomicReference main methods - get(), set(), lazySet(), compareAndSet(), weakCompareAndSet() 线程安全集合-并发集合 CopyOnWriteArrayList<E> ...
分布式计算的原语,例如AtomicLong , AtomicReference和CountDownLatch 。 Hazelcast数据结构在内存中,经过高度优化,并提供了非常低的延迟。 对于IMap上的单个get或put操作,通常可以预期往返时间不到100微秒。...
线程数## Programacion Java 2015-I ###并发变量Atomicas 锁辛克罗尼兹多斯(Sincronizados) 并发收集框架### Variables Atomicas ###### a)标量原子变量AtomicInteger / AtomicLong / AtomicBoolean ###### b)...
AtomicLong、LongAdder AtomicReference、AtomicReferenceFieldUpdater AtomicStampReference:CAS的ABA问题 原子性-synchronized 修饰代码块:大括号括起来的代码,作用于调用的对象 修饰方法:整个方法,作用于调用...
原子操作:JUC提供了一些原子操作类,如AtomicInteger、AtomicLong等,可以实现线程安全的原子操作,避免了使用synchronized关键字的性能损耗。 锁机制:JUC提供了Lock接口和Condition接口,可以实现更细粒度的锁...
原子操作是不可再分割的基本操作,JUC 提供了一系列原子操作类,如 AtomicInteger、AtomicLong 等。 4. 同步器(Synchronizers):JUC 中的同步器主要通过 AQS(AbstractQueuedSynchronizer)提供支持。
Java concurrency之AtomicLongArray原子类_动力节点Java学院整理,动力节点口口相传的Java黄埔军校
增加对 android 版本序列化的 AtomicInteger/AtomicLong 支持 修改下划线或者相似属性重复时解析结果不对的问题 #1089 反序列化增强对非静态内嵌类的支持,提供更友好的出错信息 #1082 新增反序列化特性 Feature....
也就是说调用者能够直接操作对象字段 ,那么就可以反射进行原子操作。 对于父类的字段,子类是不能直接操作的,尽管子类可以访问父类的字段。 只能是实例变量,不能是类变量,也就是说不能加static关键字。 ...
jmh-样本 一些 JMH - Java Microbenchmark Harness Samples 包含一些 JMH 示例代码。 地图推杆 比较 ConcurrentHashMap 与同步映射 ...比较 AtomicLong 与 LongAdder 随机基准 比较 Random 与 ThreadLocalRandom