Concurrent Collections

The java.util.concurrent package includes a number of additions to the Java Collections Framework. These are most easily categorized by the collection interfaces provided:

  • BlockingQueue defines a first-in-first-out data structure that blocks or times out when you attempt to add to a full queue, or retrieve from an empty queue.
  • ConcurrentMap is a subinterface of java.util.Map that defines useful atomic operations. These operations remove or replace a key-value pair only if the key is present, or add a key-value pair only if the key is absent. Making these operations atomic helps avoid synchronization. The standard general-purpose implementation of ConcurrentMap isConcurrentHashMap, which is a concurrent analog of HashMap.
  • ConcurrentNavigableMap is a subinterface of ConcurrentMap that supports approximate matches. The standard general-purpose implementation of ConcurrentNavigableMap is ConcurrentSkipListMap, which is a concurrent analog of TreeMap.

All of these collections help avoid Memory Consistency Errors by defining a happens-before relationship between an operation that adds an object to the collection with subsequent operations that access or remove that object.

Atomic Variables

The java.util.concurrent.atomic package defines classes that support atomic operations on single variables. All classes haveget and set methods that work like reads and writes on volatile variables. That is, a set has a happens-before relationship with any subsequent get on the same variable. The atomic compareAndSet method also has these memory consistency features, as do the simple atomic arithmetic methods that apply to integer atomic variables.

To see how this package might be used, let's return to the Counter class we originally used to demonstrate thread interference:

class Counter {
private int c = 0; public void increment() {
c++;
} public void decrement() {
c--;
} public int value() {
return c;
} }

One way to make Counter safe from thread interference is to make its methods synchronized, as in SynchronizedCounter:

class SynchronizedCounter {
private int c = 0; public synchronized void increment() {
c++;
} public synchronized void decrement() {
c--;
} public synchronized int value() {
return c;
} }

For this simple class, synchronization is an acceptable solution. But for a more complicated class, we might want to avoid the liveness impact of unnecessary synchronization. Replacing the int field with an AtomicInteger allows us to prevent thread interference without resorting to synchronization, as in AtomicCounter:

import java.util.concurrent.atomic.AtomicInteger;

class AtomicCounter {
private AtomicInteger c = new AtomicInteger(0); public void increment() {
c.incrementAndGet();
} public void decrement() {
c.decrementAndGet();
} public int value() {
return c.get();
} }

译文:
java.util.concurrent包中包含了许多Java集合框架。这里有许多通过提供接口容易分类的:

  • BlockingQueue 定义了先进先出的数据结构,在你尝试向满队列中添加元素,或者从空队列中检索的时候会出现阻止或超时。
  • ConcurrentMap是java.util.Map的一个子类,定义了有用的原子操作。这些操作删除或者更换一个键-值对只要键替换或者增加一个键不存在的键-值对。标准实现ConcurrenMap的是ConcurrentHashMap,这是HashMap的并发模式。
  • ConcurrentNavigableMap是ConcurrentMap的一个子接口支持近似匹配。标准实现ConcurrentNavigableMap的是ConcurrentSkipListMap,它是并发模式下的TreeMap。

  所有的这些集合都是避免Memory Consistency Errors通过定义在操作之前实现发生关系的并增加了一个对象添加到集合的后续操作如访问和删除该对象。
原子变量
  java.util.concurrent.atomic包中定义了支持在一个单变量中支持原子操作的许多类。所有的类都有get和set方法就像Volatile变量的reads和writes方法一样。也就是,set方法发生在相关相关性操作之前伴随着任何子类,get也是一样的。原子性的操作CompareAndSet方法也有内存一致性特性。为了看这个包如何使用,让我们返回Conter类我们原来实现的线程接口如下:

 class Counter {
private int c = 0; public void increment() {
c++;
} public void decrement() {
c--;
} public int value() {
return c;
} }

  一种使Connter方法更加安全是实现线程接口的时候使它的方法同步,如SynchronizedCounter:

 class SynchronizedCounter {
private int c = 0; public synchronized void increment() {
c++;
} public synchronized void decrement() {
c--;
} public synchronized int value() {
return c;
} }

  对于这个简单的类,synchronization是一个可以接受的解决方法,但是对于更复杂的类,我们可能想避免Liveness影响不必要的synchronization.替代整数域用原子整数,允许我们阻止线程接口而不是利用synchronization,就像AtomicCounter:

 import java.util.concurrent.atomic.AtomicInteger;

 class AtomicCounter {
private AtomicInteger c = new AtomicInteger(0); public void increment() {
c.incrementAndGet();
} public void decrement() {
c.decrementAndGet();
} public int value() {
return c.get();
} }

【翻译二十二】java-并发之集合与原子变量的更多相关文章

  1. JAVA之旅(二十二)——Map概述,子类对象特点,共性方法,keySet,entrySet,Map小练习

    JAVA之旅(二十二)--Map概述,子类对象特点,共性方法,keySet,entrySet,Map小练习 继续坚持下去吧,各位骚年们! 事实上,我们的数据结构,只剩下这个Map的知识点了,平时开发中 ...

  2. Java进阶(二十五)Java连接mysql数据库(底层实现)

    Java进阶(二十五)Java连接mysql数据库(底层实现) 前言 很长时间没有系统的使用java做项目了.现在需要使用java完成一个实验,其中涉及到java连接数据库.让自己来写,记忆中已无从搜 ...

  3. JAVA基础知识总结:一到二十二全部总结

    >一: 一.软件开发的常识 1.什么是软件? 一系列按照特定顺序组织起来的计算机数据或者指令 常见的软件: 系统软件:Windows\Mac OS \Linux 应用软件:QQ,一系列的播放器( ...

  4. 二十二、OGNL的一些其他操作

    二十二.OGNL的一些其他操作 投影 ?判断满足条件 动作类代码: ^ $   public class Demo2Action extends ActionSupport {     public ...

  5. 备忘录模式 Memento 快照模式 标记Token模式 行为型 设计模式(二十二)

    备忘录模式 Memento   沿着脚印,走过你来时的路,回到原点.     苦海翻起爱恨   在世间难逃避命运   相亲竟不可接近   或我应该相信是缘份   一首<一生所爱>触动了多少 ...

  6. (C/C++学习笔记) 二十二. 标准模板库

    二十二. 标准模板库 ● STL基本介绍 标准模板库(STL, standard template library): C++提供的大量的函数模板(通用算法)和类模板. ※ 为什么我们一般不需要自己写 ...

  7. 智课雅思词汇---二十二、-al即是名词性后缀又是形容词后缀

    智课雅思词汇---二十二.-al即是名词性后缀又是形容词后缀 一.总结 一句话总结: 后缀:-al ②[名词后缀] 1.构成抽象名词,表示行为.状况.事情 refusal 拒绝 proposal 提议 ...

  8. [分享] IT天空的二十二条军规

    Una 发表于 2014-9-19 20:25:06 https://www.itsk.com/thread-335975-1-1.html IT天空的二十二条军规 第一条.你不是什么都会,也不是什么 ...

  9. Bootstrap <基础二十二>超大屏幕(Jumbotron)

    Bootstrap 支持的另一个特性,超大屏幕(Jumbotron).顾名思义该组件可以增加标题的大小,并为登陆页面内容添加更多的外边距(margin).使用超大屏幕(Jumbotron)的步骤如下: ...

随机推荐

  1. android中返回键捕获处理

    在android平台上捕获Back键事件,主要用来处理返回的相关逻辑,下列几种方法都可以捕获,如下所示: 1.获取按钮按下事件,兼容android 1.0到android 2.1,重写onKeyDow ...

  2. 解决html5 video不能播放 能播放声音不能播放视频

    <video id="playVideo" style="width:90%; height:auto;" controls poster=". ...

  3. python成长之路 :线程、进程和协程

    python线程 进程与线程的历史 我们都知道计算机是由硬件和软件组成的.硬件中的CPU是计算机的核心,它承担计算机的所有任务. 操作系统是运行在硬件之上的软件,是计算机的管理者,它负责资源的管理和分 ...

  4. struts2和hibernate整合的小Demo

    jar包下载地址 创建一个web项目. 导入jar包 配置web.xml <?xml version="1.0" encoding="UTF-8"?> ...

  5. django中抽象基类的Foreignkey的定义

    class base(models.Model): user = models.ForeignKey(User) class Meta: abstract =True 以上是抽象基类的定义,只有一个公 ...

  6. Centos安装firefox/chrome

    centos安装chrome:去官网下载chrome安装包(xxx.rpm),带软件安装工具的系统双击该xxx.rpm就能自动安装,或者sudo rpm -i xxx.rpm安装. centos卸载自 ...

  7. java微信接口之——获取access_token

    本文转自http://www.cnblogs.com/always-online/category/598553.html 一.微信获取access_token接口简介 1.请求:该请求是GET方式请 ...

  8. Remove Duplicate Letters I & II

    Remove Duplicate Letters I Given a string which contains only lowercase letters, remove duplicate le ...

  9. linux /usr/bin/ld cannot find 解决

    问题: 在linux环境编译应用程式或lib的source code时常常会出现如下的错误讯息: /usr/bin/ld: cannot find -lxxx 这些讯息会随着编译不同类型的source ...

  10. MPlayer-2016-bin-noConsole

    运行 Install-RMenu.cmd 添加右键播放功能 ; 往前0.05秒 大概10多个帧 ' 往后0.05秒 大概10多个帧 鼠标右键 快速定位 鼠标中键 退出 F1 缩小 F2 原始大小 F3 ...