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. Kali Linux渗透基础知识整理(二)漏洞扫描

    Kali Linux渗透基础知识整理系列文章回顾 漏洞扫描 网络流量 Nmap Hping3 Nessus whatweb DirBuster joomscan WPScan 网络流量 网络流量就是网 ...

  2. Git-it字典翻译

    Git-it字典翻译 下面的内容翻译自git-it/dictionary 水平有限,翻译欠佳. Git准备工作 创建一个新的文件夹(目录) $ mkdir <目录名称> 切换到这个目录 ( ...

  3. centos 无线网卡安装,网卡rtl8188ee

    驱动: http://www.realtek.com.tw/downloads/downloadsView.aspx?Langid=1&PNid=48&PFid=48&Leve ...

  4. mysql导入导出数据库命令

    1.导出数据库:mysqldump -u 用户名 -p 数据库名 > 导出的文件名 如我输入的命令行: mysqldump -u root -p news > /home/jason/sq ...

  5. Reorder array to construct the minimum number

    Construct minimum number by reordering a given non-negative integer array. Arrange them such that th ...

  6. 【leetcode】Unique Binary Search Trees II

    Unique Binary Search Trees II Given n, generate all structurally unique BST's (binary search trees) ...

  7. ACM/ICPC 之 BFS+状态压缩(POJ1324(ZOJ1361))

    求一条蛇到(1,1)的最短路长,题目不简单,状态较多,需要考虑状态压缩,ZOJ的数据似乎比POj弱一些 POJ1324(ZOJ1361)-Holedox Moving 题意:一条已知初始状态的蛇,求其 ...

  8. Python 之 【re模块的正则表达式学习】

    摘要: re模块包括操作正则表达式的函数,一些工作中都需要用到,现在说明下使用方法. 使用说明: 一,re模块下的函数:            函数             描述 compile(pa ...

  9. Centos 用户登录失败N次后锁定用户禁止登陆

    针对linux上的用户,如果用户连续3次登录失败,就锁定该用户,几分钟后该用户再自动解锁 Linux有一个pam_tally2.so的PAM模块,来限定用户的登录失败次数,如果次数达到设置的阈值,则锁 ...

  10. nyoj739_笨蛋难题四

    笨蛋难题四 时间限制:1000 ms  |  内存限制:65535 KB 难度:3   描述 这些日子笨蛋一直研究股票,经过调研,终于发现xxx公司股票规律,更可喜的是 笨蛋推算出这家公司每天的股价, ...