java.util.concurrent学习

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]基于链表实现的
LinkedBlockingDequeAn 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** 接口定义

方法说明内部实现理解
tryTransferTransfers the element to a waiting consumer immediatelyxfer(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 elapsesxfer(e, true, TIMED, unit.toNanos(timeout))
transferxfer(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定义说明
ConcurrentHashMapThe 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线程安全的
ConcurrentNavigableMapextends 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
名称继承说明
Listextends Collectionvoid 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
ArrayListAbstractListObject[]
DEFAULT_CAPACITY = 10
LinkedListAbstractSequentialListtransient LinkedList.Node<E> first;
transient LinkedList.Node<E> last;
Set
名称继承说明
Setextends Collection因为无序,所以接口基本与Collection一致,但又额外增加了几个工厂函数。
SortedSetextends SetComparator<? super E> comparator();
HashSetimplements Set底层使用HashMap实现,增加了不可重复,不可以为null的限制
TreeSetimplements NavigableSetNavigableMap<E,Object>
LinkedHashSetextends HashSetHash 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
EnumSetextends AbstractSetEnum<?>[]
NavigableSetextends SortedSet
Map
名称继承说明
Collections.SynchronizedMapimplements 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();}
Hashtableextends Dictionaryvalue is not null; key is not already in the hashtable;
synchronized都在写在方法签名上的
EnumMapEnum专用Map
HashMapextends AbstractMapDEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
底层实现是Node<K,V>[]
Node<K,V> implements Map.Entry<K,V>
IdentityHashMapextends AbstractMap
LinkedHashMapextends 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>
TreeMapextends AbstractMap<K,V> implements NavigableMap<K,V>
Queue
名称继承说明
Queueextends Collection单向队列
Dequeextends Queue双向队列
Stack
名称继承说明
Stackextends Vector
Vectorextends AbstractList
Queueextends Collection
Dictionary
名称继承说明
abstract class Dictionarykeys(),
size(),
elements(),
get(key),
put(key,value),
remove(key),
isEmpty()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值