栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Parallel programming constructs in Java;并行程序;Atomicity

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Parallel programming constructs in Java;并行程序;Atomicity

文章目录
  • 1 Atomicity
  • 2 Atomic Statements in Java
    • a.Atomic Types
    • b.Non-blocking Algorithms
    • c.Locks
      • d. Counting Semaphore
      • e.Barriers
      • f. Executor


1 Atomicity

含义:最小的不会被中途插入(interleaving)的单元,换句话说:要么完成,要么不做。
但是也会产生同步错误因为 memory consistency errors
优点:使用atomically 访问可以避免synchronization
使用场景:更高性能,但更难,容易出错,通常在需要高度优化代码时使用。

2 Atomic Statements in Java
operationdoc
Reads and writes of reference variablesreference : always object ;holds a reference to information
Reads and writes of most primitive variablesAtomic for 32bit values,not sure for float and other type depends on the system
Reads and writes of all variables declared volatilenot perform a mutual exclusive lock compare to synchronized
Not atomic are multiple, combined accessesx=y+1; increase and decrease
a.Atomic Types

b.Non-blocking Algorithms

Non-blocking含义:一个thread的失败并不能导致其他thread阻塞或失败
Non-blocking Algorithms:allows threads to access shared state (or otherwise collaborate or communicate) without blocking the threads involved.

public class AtomicCounter {
private AtomicLong count = new AtomicLong(0);
public void increment() {
boolean updated = false;
while(!updated){
long prevCount = this.count.get();
updated = this.count.compareAndSet(prevCount, prevCount + 1);
}
}
public long count() {
return this.count.get();
}
}
c.Locks

An option to realize critical sections are locks
reentrant: 一个lock可以进入很多次

Locks: Attempted Acquisition
A synchronized block可以被视作一个lock unlock对,但没有可能退出。
所以提供了 tryLock(),不仅仅lock 还会return有没有成功上锁。

这里的lock只能被local或other其中一个拿到

d. Counting Semaphore
Semaphore(int capacity, boolean fair)

给临界区一个容capacity,只能进去n次

  • acquire(): 进入临界区,n–,阻塞线程
  • release():release n++
  • tryAcquire(): like acquire() but does not block
e.Barriers
  • CyclicBarrier(int n) : 可被重复使用,await n 次 resume
  • CountDownLatch(int n) :不可被重复使用,以后的countdown 返回迅速
  • Exchanger() :Synchronous exchange of two objects between two threads
public class BarrierDemo {
static CyclicBarrier barrier;
public static void main(String[] args) {
barrier = new CyclicBarrier(2);
new Thread(BarrierDemo::runSingleThread).start();
new Thread(BarrierDemo::runSingleThread).start();
}
public static void runSingleThread() {
try {
// Do first task
System.out.println("Reached first barrier");
barrier.await();
// Do second task
System.out.println("Reached second barrier");
barrier.await();
} catch (InterruptedException | BrokenBarrierException e) {}
}
}
f. Executor

这个需要单独写一篇。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/999506.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号