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. HDU 1024 max sum plus

    A - Max Sum Plus Plus Time Limit:1000MS     Memory Limit:32768KB     64bit IO Format:%I64d & %I6 ...

  2. 前端之js的常用用法

    js生成标签 // 将标签添加到i1里面 var tag = document.createElement('input'); tag.setAttribute('type', 'text'); ta ...

  3. 1.2---翻转字符串(CC150)

    import java.util.*; public class Reverse { public String reverseString(String iniString) { // write ...

  4. MyEclipse 优化

    1.取消自动validation 有一堆,什么xml.jsp.jsf.js等等, 我们没有必要全部都去自动校验一下,只是需要的时候才会手工校验一下! 取消方法: windows-->perfer ...

  5. [20160701]DevideByZeroWithoutNoException——from 《Java How To Program (Early Objects), 10th》

    //一段优美的例子 import java.util.Scanner; import java.util.InputMismatchException; public class DevideByZe ...

  6. 1.把二元查找树转变成排序的双向链表[BST2DoubleLinkedList]

    [题目]:输入一棵二元查找树,将该二元查找树转换成一个排序的双向链表.要求不能创建任何新的结点,只调整指针的指向. 比如将二元查找树 . 10 / \ 6 14 / \ / \ 4 8 12 16 转 ...

  7. poj3341

    AC自动机,用40^4 * 50 * 10的空间进行dp. 最大的难点在于hash. hash一个数列f,数列中的每一位都有一个上限g,即f[i]<=g[i]. 那么可以将该数列hash为这样一 ...

  8. linux学习之一些琐碎知识点

    一.python 问:django中project和app之间到底有什么不同? 答:他们的区别就是一个是配置,另一个是代码. 一个project包含很多个django app以及对它们的配置.技术上, ...

  9. storm单机环境部署

    前面说过storm集群的部署,这篇主要介绍storm单机环境部署,其实他们之间很类似,就是将之前配置文件中所有的集群条目改成本机的地址即可,部署之前应该按前面solr和zookeeper单机环境部署那 ...

  10. 20151130test->20160530

    过了6个月了,有些长进么?哈 go go go 开源镜像 http://mirrors.163.com/