Queue
阻塞队列
BlockingQueue由保证有序性
class定义 | 说明 |
---|---|
BlockingQueue | 单向阻塞队列 接口 |
BlockingDeque | 双向阻塞队列 接口 |
TransferQueue | 参照接口定义 |
ArrayBlockingQueue | [ReentrantLock]有界阻塞队列 数组实现的 |
LinkedBlockingQueue | [ReentrantLock]have higher throughput than array-based queues but less predictable performance in most concurrent applications |
SynchronousQueue | [volatile]同步的阻塞队列,一个队列中只能最多有一个元素 |
DelayQueue | [ReentrantLock]An unbounded blocking queue of Delayed elements, in which an element can only be taken when its delay has expired. |
PriorityBlockingQueue | [ReentrantLock]核心是数组,里面的元素要么Comparable,要么使用Queue的比较方法计算优先级,然后插入。 add/put/offer使用相同的逻辑,出队时 |
LinkedTransferQueue | [volatile,VarHandle CAS]基于链表实现的 |
LinkedBlockingDeque | An optionally-bounded blocking deque based on linked nodes |
ConcurrentLinkedQueue | [CAS非阻塞算法] |
ConcurrentLinkedDeque |
PriorityBlockingQueue
private E dequeue() {
// assert lock.isHeldByCurrentThread();
final Object[] es;
final E result;
// 取数组0位
if ((result = (E) ((es = queue)[0])) != null) {
final int n;
final E x = (E) es[(n = --size)];
es[n] = null;
if (n > 0) {
final Comparator<? super E> cmp;
if ((cmp = comparator) == null)
siftDownComparable(0, x, es, n);
else
siftDownUsingComparator(0, x, es, n, cmp);
}
}
return result;
}
LinkedBlockingQueue入列出列
private void enqueue(Node<E> node) {
// assert putLock.isHeldByCurrentThread();
// assert last.next == null;
last = last.next = node;
// last.next = node // 入队
// last = last.next // 移动指针
}
private E dequeue() {
// assert takeLock.isHeldByCurrentThread();
// assert head.item == null;
Node<E> h = head;
Node<E> first = h.next; // 缓存新的头
h.next = h; // help GC // h不再引用其他对象,帮助gc回收
head = first; // 移动头指针,前一个头不再被引用
E x = first.item; // 取数据
first.item = null; // 头没有数据,清空数据
return x; // 返回数据
}
TransferQueue** 接口定义
方法 | 说明 | 内部实现 | 理解 |
---|---|---|---|
tryTransfer | Transfers the element to a waiting consumer immediately | xfer(e, true, NOW, 0) | 必须有等待队列才会被消费,否则就丢弃了 |
tryTransfer(E e, long timeout, TimeUnit unit) | Transfers the element to a consumer if it is possible to do so before the timeout elapses | xfer(e, true, TIMED, unit.toNanos(timeout)) | |
transfer | xfer(e, true, SYNC, 0) | 同步的,放入队列后被消费才会继续生产 | |
hasWaitingConsumer | |||
getWaitingConsumerCount |
List
class定义 | 说明 |
---|---|
CopyOnWriteArrayList | 【synchronized】The “snapshot” style iterator method uses a reference to the state of the array at the point that the iterator was created. 每次写都会先建立一个副本,对副本操作,操作完成之后,setArray |
Map
class定义 | 说明 |
---|---|
ConcurrentHashMap | The primary design goal of this hash table is to maintain concurrent readability (typically method get(), but also iterators and related methods) while minimizing update contention. Secondary goals are to keep space consumption about the same or better than java.util.HashMap, and to support high initial insertion rates on an empty table by many threads. |
ConcurrentMap | 线程安全的 |
ConcurrentNavigableMap | extends ConcurrentMap<K,V>, NavigableMap<K,V> |
ConcurrentSkipListMap |
ConcurrentHashMap
public V get(Object key) {
Node<K,V>[] tab; Node<K,V> e, p; int n, eh; K ek;
int h = spread(key.hashCode());
if ((tab = table) != null && (n = tab.length) > 0 &&
(e = tabAt(tab, (n - 1) & h)) != null) {
if ((eh = e.hash) == h) {
if ((ek = e.key) == key || (ek != null && key.equals(ek)))
return e.val;
}
else if (eh < 0)
return (p = e.find(h, key)) != null ? p.val : null;
while ((e = e.next) != null) {
if (e.hash == h &&
((ek = e.key) == key || (ek != null && key.equals(ek))))
return e.val;
}
}
return null;
}
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; K fk; V fv;
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)))
break; // no lock when adding to empty bin
}
else if ((fh = f.hash) == MOVED)
tab = helpTransfer(tab, f);
else if (onlyIfAbsent // check first node without acquiring lock
&& fh == hash
&& ((fk = f.key) == key || (fk != null && key.equals(fk)))
&& (fv = f.val) != null)
return fv;
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);
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;
}
}
else if (f instanceof ReservationNode)
throw new IllegalStateException("Recursive update");
}
}
if (binCount != 0) {
if (binCount >= TREEIFY_THRESHOLD)
treeifyBin(tab, i);
if (oldVal != null)
return oldVal;
break;
}
}
}
addCount(1L, binCount);
return null;
}
Set
class定义 | 说明 |
---|---|
ConcurrentSkipListSet | |
CopyOnWriteArraySet | 【内部由CopyOnWriteArrayList维护数据】 It is best suited for applications in which set sizes generally stay small, read-only operations vastly outnumber mutative operations, and you need to prevent interference among threads during traversal。 |
Task
class定义 | 说明 |
---|---|
FutureTask | |
ForkJoinTask | |
RecursiveTask |
Executor
class定义 | 说明 |
---|---|
AbstractExecutorService | |
Executor | |
ExecutorCompletionService | |
ScheduledExecutorService | |
ScheduledThreadPoolExecutor | |
Executors | |
ExecutorService |
Future
class定义 | 说明 |
---|---|
Future | |
RunnableFuture | |
RunnableScheduledFuture | |
ScheduledFuture | |
CompletableFuture |
class定义 | 说明 |
---|---|
BrokenBarrierException | |
CancellationException | |
CompletionException | |
ExecutionException | |
RejectedExecutionException | |
TimeoutException | |
Callable | |
CompletionService | |
CompletionStage | |
CountDownLatch | |
CountedCompleter | |
CyclicBarrier | |
Delayed | |
Exchanger | |
Flow | |
ForkJoinPool | |
ForkJoinWorkerThread | |
Helpers | |
Phaser | |
RecursiveAction | |
RejectedExecutionHandler | |
Semaphore | |
SubmissionPublisher | |
ThreadFactory | |
ThreadLocalRandom | |
ThreadPoolExecutor | |
TimeUnit |
Java 集合
Iterator
boolean hasNext();
E next();
default void remove() {
throw new UnsupportedOperationException("remove");
}
default void forEachRemaining(Consumer<? super E> action) {
Objects.requireNonNull(action);
while (hasNext())
action.accept(next());
}
Collection
extends Iterator
add
addAll
clear
contains
containsAll
equals
hashCode
isEmpty
iterator
parallelStream
remove
removeAll
removeIf
retainAll
size
spliterator
stream
toArray
toArray
toArray
List
有序可重复
void add(int index, E element);
boolean addAll(int index, Collection<? extends E> c);
static <E> List<E> copyOf(Collection<? extends E> coll)
get
indexOf
lastIndexOf
ListIterator<E> listIterator();
ListIterator<E> listIterator(int index);
static <E> List<E> of() {
static <E> List<E> of(E... elements) {
switch (elements.length) { // implicit null check of elements
case 0:
return ImmutableCollections.emptyList();
case 1:
return new ImmutableCollections.List12<>(elements[0]);
case 2:
return new ImmutableCollections.List12<>(elements[0], elements[1]);
default:
return new ImmutableCollections.ListN<>(elements);
}
}
E remove(int index);
default void replaceAll(UnaryOperator<E> operator)
E set(int index, E element)
List<E> subList(int fromIndex, int toIndex);
default void sort(Comparator<? super E> c)
spliterator
名称 | 继承 | 说明 |
---|---|---|
List | extends Collection | void add(int index, E element); boolean addAll(int index, Collection<? extends E> c); static <E> List<E> copyOf(Collection<? extends E> coll) get indexOf lastIndexOf ListIterator<E> listIterator(); ListIterator<E> listIterator(int index); static <E> List<E> of() { static <E> List<E> of(E... elements) { switch (elements.length) { // implicit null check of elements case 0: return ImmutableCollections.emptyList(); case 1: return new ImmutableCollections.List12<>(elements[0]); case 2: return new ImmutableCollections.List12<>(elements[0], elements[1]); default: return new ImmutableCollections.ListN<>(elements); } } E remove(int index); default void replaceAll(UnaryOperator<E> operator) E set(int index, E element) List<E> subList(int fromIndex, int toIndex); default void sort(Comparator<? super E> c) spliterator |
ArrayList | AbstractList | Object[] DEFAULT_CAPACITY = 10 |
LinkedList | AbstractSequentialList | transient LinkedList.Node<E> first; transient LinkedList.Node<E> last; |
Set
名称 | 继承 | 说明 |
---|---|---|
Set | extends Collection | 因为无序,所以接口基本与Collection一致,但又额外增加了几个工厂函数。 |
SortedSet | extends Set | Comparator<? super E> comparator(); |
HashSet | implements Set | 底层使用HashMap实现,增加了不可重复,不可以为null的限制 |
TreeSet | implements NavigableSet | NavigableMap<E,Object> |
LinkedHashSet | extends HashSet | Hash table and linked list implementation of the Set interface, with predictable iteration order. This implementation differs from HashSet in that it maintains a doubly-linked list running through all of its entries |
EnumSet | extends AbstractSet | Enum<?>[] |
NavigableSet | extends SortedSet |
Map
名称 | 继承 | 说明 |
---|---|---|
Collections.SynchronizedMap | implements Map<K,V> | 构造函数一:SynchronizedMap(Map<K,V> m) {this.m = Objects.requireNonNull(m);mutex = this;}} ;构造函数二: SynchronizedMap(Map<K,V> m, Object mutex) {this.m = m;this.mutex = mutex;} ;在每一个方法实现中加锁; synchronized (mutex) {return m.size();} |
Hashtable | extends Dictionary | value is not null; key is not already in the hashtable; synchronized都在写在方法签名上的 |
EnumMap | Enum专用Map | |
HashMap | extends AbstractMap | DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16 底层实现是Node<K,V>[] Node<K,V> implements Map.Entry<K,V> |
IdentityHashMap | extends AbstractMap | |
LinkedHashMap | extends HashMap | 是一个key按照加入顺序有序的HashMap Note that this implementation is not synchronized; 如何实现线程同步? Map m = Collections.synchronizedMap(new LinkedHashMap(...)) |
NavigableMap<K,V> | extends SortedMap | |
SortedMap<K,V> | extends Map<K,V> | |
TreeMap | extends AbstractMap<K,V> implements NavigableMap<K,V> |
Queue
名称 | 继承 | 说明 |
---|---|---|
Queue | extends Collection | 单向队列 |
Deque | extends Queue | 双向队列 |
Stack
名称 | 继承 | 说明 |
---|---|---|
Stack | extends Vector | |
Vector | extends AbstractList | |
Queue | extends Collection |
Dictionary
名称 | 继承 | 说明 |
---|---|---|
abstract class Dictionary | keys(), size(), elements(), get(key), put(key,value), remove(key), isEmpty() |