并发容器专门为并发而生的,最常用的就是ConcurrentHashMap、BlockingQueue了,这两个并发容器是我们比较常用的,前者取代同步Map提供了很好的并发性,后者提供了一种生产者与消费者模式的队列,ConcurrentHashMap官方介绍说了,它并没有提供在Map上加锁独占访问,这说明什么?这说明它在原子性上是没有保障的,但是它在内存可见性上是完全保证的,也就说如果你需要使用独立的线程初始化它,并且保证写并发很小的情况下,它是一个很好的缓存容器,当然我们在程序中通常也是这么用的。
下面看一个实例:
package com.home.thread.thread9; import java.util.concurrent.ConcurrentHashMap; /** * @author gaoxu * 实践出真知! */ public class ConcurrentHashMapInstance { static ConcurrentHashMap<?, ?> chm = null; /** * 获取ConcurrentHashMap的全局对象 * * @return */ public synchronized static ConcurrentHashMap<?, ?> getCHM() { if (chm == null) { chm = new ConcurrentHashMap<String, Boolean>(); } return chm; } }
单实例的ConcurrentHashMap是一个缓存服务容器,当然是一个简陋的,通常我们会在程序启动时对其进行初始化,可以开一个线程做这件事,在这同时它的实例就已经可以对外提供服务了并且是并发的。而我们通常使用的HashMap经过同步处理也可以实现多线程缓存的服务,但是它是一个同步的操作。对于同样是Map的操作,并发性就要差了好多。
BlockingQueue就更有用了,我们经常会遇到这样的场景生产者和消费者模式,正好可以使用它来实现一个这样的中间件,当然也是很简陋的,最关键的是我们可以在这个所谓的中间件上任意的实现业务逻辑。
还有一个并发容器是我们会经常使用的,那就是ConurrentLinkedQueue,先进先出队列,它正好可以取代我们平时使用的LinkedList的方式,我们来看一个使用LinkedList来实现的对列实例。
package com.uskytec.ubs.foundation.queue; import java.util.ArrayList; import java.util.LinkedList; /** * @author gaoxu * 实践出真知! */ public class RoleResourceQueue { private static RoleResourceQueue instance = null; private RoleResourceQueue() { } public synchronized static RoleResourceQueue getInstance() { if (instance == null) instance = new RoleResourceQueue(); return instance; } private final static LinkedList<RoleResourceQueueEntity> cache = new LinkedList<RoleResourceQueueEntity>(); public synchronized int add(RoleResourceQueueEntity xml) { cache.addLast(xml); return 1; } public synchronized int batchAdd(ArrayList<RoleResourceQueueEntity> xml) { int xmlCount = xml.size(); int j = 0; for (int i = 0; i < xmlCount; i++) { RoleResourceQueueEntity apSubmit = xml.get(i); cache.addLast(apSubmit); j++; } return j; } public synchronized RoleResourceQueueEntity get() { if (cache != null && cache.size() > 0) return cache.removeFirst(); return null; } public synchronized int getCount() { if (cache != null) return cache.size(); return 0; } }当然还有许多没有介绍的并发容器,大多可能都是我们不常用的,如果需要可以查看jdk说明。