1.集合框架图
参考网上一张图:
简述:
如图所示,java中容器接口主要是两大类,java.util.map和java.util.collection。本质上两大类容器都一样都是存放数据的。如果细分起来就是collection容器是存放一个对象一个对象。而map是存放一对一对key value的。但是如果把map存放key value对象当成一个entry对象,那么和collection容器就是一样的。
2.map集合容器发展
java最开始使用的hashtable来实现map集合的存储,hashtable的特点是不管是插入数据还是读取数据,都会进行synchronized。虽然这么做保证了线程安全,但是带来的就是代码效率低下。
为了解决hashtable加锁带来的性能低下问题,出现了hashmap实现。hashmap和hashtable本质上的区别就是hashmap是完全不加锁的。这个在单线程下是没有问题的。但是在多线程并发的情况是有问题的。
为了解决hashmap无锁带来的线程安全问题,出现了Collections.synchronizedMap(new HashMap<String, String>()) 我们可以通过该方式创建一个带保存和读取都带锁的的synchronizedMap,读取源码可以知道他跟hashtable方式差不多,都是加锁的。
最后java出现了ConcurrentHashMap 这种集合实现方式。这种集合使用cas方式保证多线程并发保存问题。这种方式在保存写入的时候(需要有一定数据量测试下),比上面hashtable效率低。因为ConcurrentHashMap在保存的时候需要做各种cas判断,本来是链表结构,到8之后又变成红黑树结构。该ConcurrentHashMap真正的优势是在读的方面。因为内部是已经排好序的数据结构,所以读的效率会比较高。所以该集合方式在写少读多情景下有优势
ConcurrentHashMap 在保存数据的数据是如何保证数据安全的呢?我们看下源码
可以看出,ConcurrentHashMap 在部分关键部分加锁。其他部分使用cas操作
/** Implementation for put and putIfAbsent */
final V putVal(K key, V value, boolean onlyIfAbsent) {
if (key == null || value == null) throw new NullPointerException();
int hash = spread(key.hashCode());
int binCount = 0;
for (Node<K,V>[] tab = table;;) {
Node<K,V> f; int n, i, fh;
if (tab == null || (n = tab.length) == 0)
tab = initTable();
else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) {
if (casTabAt(tab, i, null,
new Node<K,V>(hash, key, value, null)))
break; // no lock when adding to empty bin
}
else if ((fh = f.hash) == MOVED)
tab = helpTransfer(tab, f);
else {
V oldVal = null;
synchronized (f) {
if (tabAt(tab, i) == f) {
if (fh >= 0) {
binCount = 1;
for (Node<K,V> e = f;; ++binCount) {
K ek;
if (e.hash == hash &&
((ek = e.key) == key ||
(ek != null && key.equals(ek)))) {
oldVal = e.val;
if (!onlyIfAbsent)
e.val = value;
break;
}
Node<K,V> pred = e;
if ((e = e.next) == null) {
pred.next = new Node<K,V>(hash, key,
value, null);
break;
}
}
}
else if (f instanceof TreeBin) {
Node<K,V> p;
binCount = 2;
if ((p = ((TreeBin<K,V>)f).putTreeVal(hash, key,
value)) != null) {
oldVal = p.val;
if (!onlyIfAbsent)
p.val = value;
}
}
}
}
if (binCount != 0) {
if (binCount >= TREEIFY_THRESHOLD)
treeifyBin(tab, i);
if (oldVal != null)
return oldVal;
break;
}
}
}
addCount(1L, binCount);
return null;
}
/**
* Adds to count, and if table is too small and not already
* resizing, initiates transfer. If already resizing, helps
* perform transfer if work is available. Rechecks occupancy
* after a transfer to see if another resize is already needed
* because resizings are lagging additions.
*
* @param x the count to add
* @param check if <0, don't check resize, if <= 1 only check if uncontended
*/
private final void addCount(long x, int check) {
CounterCell[] as; long b, s;
if ((as = counterCells) != null ||
!U.compareAndSwapLong(this, BASECOUNT, b = baseCount, s = b + x)) {
CounterCell a; long v; int m;
boolean uncontended = true;
if (as == null || (m = as.length - 1) < 0 ||
(a = as[ThreadLocalRandom.getProbe() & m]) == null ||
!(uncontended =
U.compareAndSwapLong(a, CELLVALUE, v = a.value, v + x))) {
fullAddCount(x, uncontended);
return;
}
if (check <= 1)
return;
s = sumCount();
}
if (check >= 0) {
Node<K,V>[] tab, nt; int n, sc;
while (s >= (long)(sc = sizeCtl) && (tab = table) != null &&
(n = tab.length) < MAXIMUM_CAPACITY) {
int rs = resizeStamp(n);
if (sc < 0) {
if ((sc >>> RESIZE_STAMP_SHIFT) != rs || sc == rs + 1 ||
sc == rs + MAX_RESIZERS || (nt = nextTable) == null ||
transferIndex <= 0)
break;
if (U.compareAndSwapInt(this, SIZECTL, sc, sc + 1))
transfer(tab, nt);
}
else if (U.compareAndSwapInt(this, SIZECTL, sc,
(rs << RESIZE_STAMP_SHIFT) + 2))
transfer(tab, null);
s = sumCount();
}
}
}
我们一定很好奇既然有ConcurrentHashMap 那么对应的应该要有ConcurrentHashTree类似的集合实现。但是很遗憾并没有。因为tree这种集合如果使用cas保证线程安全太复杂了。但是有时候,我们需要一个排好序的map集合,这个时候出现了ConcurrentSkipListMap,底层使用跳表结构的。什么是跳表呢?个人简单的理解是类似于平衡二叉树的结构(不一定对),大家可以去网上找些资料自己看下。举例如下图:加入我们想找到14这个数怎么找呢?第一我们从level3这级找,发现14在header-21之间,好,然后我们到level2进一步找发现在7-21之间,然后跳到level1的7-21上查询,发现刚好第二个数就是14,于是数据就找到了
3.collection集合容器历程
最开始使用的vector集合方式,这种集合方式和hashtable一样都是不管保存还是读取都是synchronized加锁。
后面出现ArrayList和Set集合,这两种集合本质上是一样的,区别是set是去重的。但是他们保存和读取都不加锁,在多线程并发情况下是有问题的。
后面出现CopyOnWriteArrayList,看名字即可知道是写时复制,他的原理是当有个线程需要往集合中添加数据的时候,在内存中拷贝一份和原来集合一模一样的数据,并在新拷贝集合后面新增一个空间来保存需要新增的数据。当数据保存成功后,将原来集合的引用重新指向新建的集合。源码如下:
/**
* Appends the specified element to the end of this list.
*
* @param e element to be appended to this list
* @return {@code true} (as specified by {@link Collection#add})
*/
public boolean add(E e) {
final ReentrantLock lock = this.lock;//使用CAS的方式
lock.lock();
try {
Object[] elements = getArray();
int len = elements.length;
Object[] newElements = Arrays.copyOf(elements, len + 1);//拷贝一份新数据并比原来的数据多一个空间用来存储即将保存的新数据
newElements[len] = e;
setArray(newElements); //将集合引用指向新创建的集合
return true;
} finally {
lock.unlock();
}
}
后面出现Queue队列是专门来针对多线程高并发情况的容器。里面使用cas操作来保证线程安全。下面看下poll方法获取队列元素的源码。可以明显看到使用的无锁的CAS操作
public E poll() {
restartFromHead:
for (;;) {
for (Node<E> h = head, p = h, q;;) {
E item = p.item;
if (item != null && p.casItem(item, null)) {
// Successful CAS is the linearization point
// for item to be removed from this queue.
if (p != h) // hop two nodes at a time
updateHead(h, ((q = p.next) != null) ? q : p);
return item;
}
else if ((q = p.next) == null) {
updateHead(h, p);
return null;
}
else if (p == q)
continue restartFromHead;
else
p = q;
}
}
}
也可以看下add方法,本质上是调用offer方法。进入查看可以看出使用的cas的方式。
/**
* Inserts the specified element at the tail of this queue.
* As the queue is unbounded, this method will never throw
* {@link IllegalStateException} or return {@code false}.
*
* @return {@code true} (as specified by {@link Collection#add})
* @throws NullPointerException if the specified element is null
*/
public boolean add(E e) {
return offer(e);
}
public boolean offer(E e) {
checkNotNull(e);
final Node<E> newNode = new Node<E>(e);
for (Node<E> t = tail, p = t;;) {
Node<E> q = p.next;
if (q == null) {
// p is last node
if (p.casNext(null, newNode)) {
// Successful CAS is the linearization point
// for e to become an element of this queue,
// and for newNode to become "live".
if (p != t) // hop two nodes at a time
casTail(t, newNode); // Failure is OK.
return true;
}
// Lost CAS race to another thread; re-read next
}
else if (p == q)
// We have fallen off list. If tail is unchanged, it
// will also be off-list, in which case we need to
// jump to head, from which all live nodes are always
// reachable. Else the new tail is a better bet.
p = (t != (t = tail)) ? t : head;
else
// Check for tail updates after two hops.
p = (p != t && t != (t = tail)) ? t : q;
}
}
4.常见的各种Queue
有道常见的面试题:就是Queue和List的区别是什么?
区别主要是Queue增加了许多对线程友好的API如poll(取出数据,并remove) peek(只取出数据) offer(保存数据,会返回boolean类型告诉线程保存成功还是失败)比较常见使用的应该是Queue的子类BlockingQueue提供的put take都是阻塞的。
BlockingQueue 是一个接口,这个接口非常重要,在线程池的使用中,多种队列基本都是他的实现类
下面我们来看下该接口都有哪几种实现的集合方式
1.LinkedBlockingDeque
该实现方式,容器最大考验容纳Integer.MAX_VALUE 个。这个大家可以去查看下源码就可以知道
/**
* Creates a {@code LinkedBlockingDeque} with a capacity of
* {@link Integer#MAX_VALUE}.
*/
public LinkedBlockingDeque() {
this(Integer.MAX_VALUE);
}
2.ArrayBlockingQueue
这是一个需要我们初始化的时候需要知道队列大小的queue
/**
* Creates an {@code ArrayBlockingQueue} with the given (fixed)
* capacity and default access policy.
*
* @param capacity the capacity of this queue
* @throws IllegalArgumentException if {@code capacity < 1}
*/
public ArrayBlockingQueue(int capacity) {
this(capacity, false);
}
3.DelayQueue
从字面上理解是延迟队列。我们往队列中放入的元素必须是一个实现了Delayed接口的实现类,并且需要重写里面的getDelay 和compareTo方法。该队列主要是用来按照实际进行任务调度,举个例子,我们可以设置到哪个时间点,我们想让哪些线程先执行,哪些线程后执行,就可以使用该队列。其实本质该队列使用类似于PriorityQueue(可以去看下该源码的解释),具体使用可以去网上找些资料看下。
4.SynchronousQueue
该容器的大小始终为0。主要的用途是用在两个线程之间传递数据使用的。很像线程的一个方法Exchanger,也是用在两个线程之间传递数据。该SynchronousQueue在线程池中的用处较大,线程间互相进行任务调度都需要使用它。
5.TransferQueue
它只有唯一的一个实现类LinkedTransferQueue,该集合是SynchronousQueue的加强版,SynchronousQueue只能传递一个数据,但是LinkedTransferQueue可以传递多个数据。关键是该集合有个方法是transfer,类似于put方法,但是该方法不同于之前集合的put是当有线程调用transfer时,该线程必须阻塞直到有个线程来把该线程投递进去的数据取走,该线程才能回来继续处理接下来的代码逻辑。通俗话讲就是,货到付款。没有收到钱觉不走。