zoukankan      html  css  js  c++  java
  • Java线程安全容器

    一、Java同步容器

      同步容器是用来解决并发情况下的容器线程安全问题的。给多线程环境准备一个线程安全的容器对象。

      线程安全的容器对象: Vector, Hashtable。线程安全容器对象,都是使用synchronized方法实现的。

      concurrent包中的同步容器,大多数是使用系统底层技术实现的线程安全。类似native。Java8中使用CAS。

    二、Map/Set

    1,ConcurrentHashMap/ConcurrentHashSet

      底层哈希实现的同步Map(Set)。效率高,线程安全。使用系统底层技术实现线程安全。量级较synchronized低。key和value不能为null。

    2,ConcurrentSkipListMap/ConcurrentSkipListSet

      底层跳表(SkipList)实现的同步Map(Set)。有序,效率比ConcurrentHashMap稍低。

    三、List

    1,CopyOnWriteArrayList

      写时复制集合。写入效率低,读取效率高。每次写入数据,都会创建一个新的底层数组。

    四、Queue

    1,ConcurrentLinkedQueue

      基础链表同步队列。

    2,LinkedBlockingQueue

      阻塞队列,队列容量不足自动阻塞,队列容量为0自动阻塞。

    3,ArrayBlockingQueue

      底层数组实现的有界队列。自动阻塞。根据调用API(add/put/offer)不同,有不同特性。

      当容量不足的时候,有阻塞能力。

      add方法在容量不足的时候,抛出异常。

      put方法在容量不足的时候,阻塞等待。

      单参数offer方法,不阻塞。容量不足的时候,返回false。当前新增数据操作放弃。

      三参数offer方法(offer(value,times,timeunit)),容量不足的时候,阻塞times时长(单位为timeunit),如果在阻塞时长内,有容量空闲,新增数据返回true。如果阻塞时长范围内,无容量空闲,放弃新增数据,返回false。

    4,DelayQueue

      延时队列。根据比较机制,实现自定义处理顺序的队列。常用于定时任务。如:定时关机。

    5,LinkedTransferQueue

      转移队列,使用transfer方法,实现数据的即时处理。没有消费者,就阻塞。

    6,SynchronusQueue

      同步队列,是一个容量为0的队列。是一个特殊的TransferQueue。

      必须现有消费线程等待,才能使用的队列。

      add方法,无阻塞。若没有消费线程阻塞等待数据,则抛出异常。

      put方法,有阻塞。若没有消费线程阻塞等待数据,则阻塞。

  • 相关阅读:
    周末之个人杂想(十三)
    PowerTip of the DaySorting Multiple Properties
    PowerTip of the DayCreate Remoting Solutions
    PowerTip of the DayAdd Help to Your Functions
    PowerTip of the DayAcessing Function Parameters by Type
    PowerTip of the DayReplace Text in Files
    PowerTip of the DayAdding Extra Information
    PowerTip of the DayPrinting Results
    Win7下IIS 7.5配置SSAS(2008)远程访问
    PowerTip of the DayOpening Current Folder in Explorer
  • 原文地址:https://www.cnblogs.com/guanghe/p/10648333.html
Copyright © 2011-2022 走看看