High Level Concurrency Objects , 高级并发对象 From Oracle.com-CSDN博客
高并发对象 —— Concurrent Collections 并发集合-CSDN博客
高并发对象 —— Lock Objects 锁定目标-CSDN博客
高并发对象 —— Atomic Variables 原子变量-CSDN博客
From: https://docs.oracle.com/javase/tutorial/essential/concurrency/highlevel.html
Concurrent Random Numbers
In JDK 7, java.util.concurrent includes a convenience class, ThreadLocalRandom, for applications that expect to use random numbers from multiple threads or ForkJoinTasks.
在JDK 7中,java.util.concurrent包含了一个便捷类ThreadLocalRandom,适用于需要从多个线程或ForkJoinTasks中使用随机数的应用程序。
For concurrent access, using ThreadLocalRandom instead of Math.random() results in less contention and, ultimately, better performance.
在并发访问的情况下,使用ThreadLocalRandom替代Math.random()可以减少资源争用,最终提升性能表现。
All you need to do is call ThreadLocalRandom.current(), then call one of its methods to retrieve a random number. Here is one example:
你只需要调用ThreadLocalRandom.current(),然后调用其中一个方法来获取随机数。这里有一个示例:
int r = ThreadLocalRandom.current() .nextInt(4, 77);
ThreadLocalRandom
ThreadLocalRandom (Java Platform SE 8 )
A random number generator isolated to the current thread. Like the global Random generator used by the Math class, a ThreadLocalRandom is initialized with an internally generated seed that may not otherwise be modified. When applicable, use of ThreadLocalRandom rather than shared Random objects in concurrent programs will typically encounter much less overhead and contention. Use of ThreadLocalRandom is particularly appropriate when multiple tasks (for example, each a ForkJoinTask) use random numbers in parallel in thread pools.
一个仅限于当前线程的随机数生成器。与Math类使用的全局Random生成器类似,ThreadLocalRandom的初始化种子由内部生成且不可修改。在并发程序中,使用ThreadLocalRandom而非共享的Random对象通常能显著减少开销和竞争。当多个任务(例如ForkJoinTask)在线程池中并行使用随机数时,采用ThreadLocalRandom尤为合适。
Usages of this class should typically be of the form: ThreadLocalRandom.current().nextX(...) (where X is Int, Long, etc). When all usages are of this form, it is never possible to accidently share a ThreadLocalRandom across multiple threads.
使用此类的典型形式应为:ThreadLocalRandom.current().nextX(...)(其中X为Int、Long等类型)。当所有使用均遵循此规范时,可彻底避免在多线程间意外共享ThreadLocalRandom对象的情况。
This class also provides additional commonly used bounded random generation methods.
Instances of ThreadLocalRandom are not cryptographically secure. Consider instead using SecureRandom in security-sensitive applications. Additionally, default-constructed instances do not use a cryptographically random seed unless the system property java.util.secureRandomSeed is set to true.
该类还提供了其他常用的有界随机生成方法。
ThreadLocalRandom实例不具备密码学安全性。在安全性要求较高的应用中,请考虑改用SecureRandom。此外,除非系统属性java.util.secureRandomSeed设置为true,否则默认构造的实例不会使用加密随机的种子。
java.util.concurrent
java.util.concurrent (Java Platform SE 8 )
Utility classes commonly useful in concurrent programming. This package includes a few small standardized extensible frameworks, as well as some classes that provide useful functionality and are otherwise tedious or difficult to implement. Here are brief descriptions of the main components. See also the java.util.concurrent.locks and java.util.concurrent.atomic packages.
并发编程中常用的实用工具类。此包包含几个小型标准化可扩展框架,以及一些提供实用功能的类,这些功能若自行实现将非常繁琐或困难。以下是主要组件的简要说明。另请参阅 java.util.concurrent.locks 和 java.util.concurrent.atomic 包。
Executors
Interfaces. Executor is a simple standardized interface for defining custom thread-like subsystems, including thread pools, asynchronous I/O, and lightweight task frameworks. Depending on which concrete Executor class is being used, tasks may execute in a newly created thread, an existing task-execution thread, or the thread calling execute, and may execute sequentially or concurrently. ExecutorService provides a more complete asynchronous task execution framework. An ExecutorService manages queuing and scheduling of tasks, and allows controlled shutdown. The ScheduledExecutorService subinterface and associated interfaces add support for delayed and periodic task execution. ExecutorServices provide methods arranging asynchronous execution of any function expressed as Callable, the result-bearing analog of Runnable. A Future returns the results of a function, allows determination of whether execution has completed, and provides a means to cancel execution. A RunnableFuture is a Future that possesses a run method that upon execution, sets its results.
接口。Executor是一个简单的标准化接口,用于定义自定义类线程子系统,包括线程池、异步I/O和轻量级任务框架。根据所使用的具体Executor类,任务可以在新创建的线程、现有任务执行线程或调用execute的线程中执行,并且可以顺序或并发执行。ExecutorService提供了更完整的异步任务执行框架。ExecutorService管理任务的排队和调度,并允许受控关闭。ScheduledExecutorService子接口及相关接口增加了对延迟和周期性任务执行的支持。ExecutorServices提供了安排异步执行任何表示为Callable的函数的方法,Callable是具有返回结果的Runnable类似物。Future返回函数的结果,允许确定执行是否已完成,并提供取消执行的方法。RunnableFuture是一种Future,它具有一个run方法,执行时会设置其结果。
Implementations. Classes ThreadPoolExecutor and ScheduledThreadPoolExecutor provide tunable, flexible thread pools. The Executors class provides factory methods for the most common kinds and configurations of Executors, as well as a few utility methods for using them. Other utilities based on Executors include the concrete class FutureTask providing a common extensible implementation of Futures, and ExecutorCompletionService, that assists in coordinating the processing of groups of asynchronous tasks.
实现。ThreadPoolExecutor类和ScheduledThreadPoolExecutor类提供了可调优、灵活的线程池。Executors类为最常见的执行器类型和配置提供了工厂方法,以及一些使用它们的实用方法。基于Executors的其他工具包括具体类FutureTask(提供了Futures的通用可扩展实现)和ExecutorCompletionService(协助协调异步任务组的处理)。
Class ForkJoinPool provides an Executor primarily designed for processing instances of ForkJoinTask and its subclasses. These classes employ a work-stealing scheduler that attains high throughput for tasks conforming to restrictions that often hold in computation-intensive parallel processing.
ForkJoinPool类提供了一个Executor,主要用于处理ForkJoinTask及其子类的实例。这些类采用了一种工作窃取调度器,对于符合计算密集型并行处理常见限制条件的任务,能够实现高吞吐量。
Queues
The ConcurrentLinkedQueue class supplies an efficient scalable thread-safe non-blocking FIFO queue. The ConcurrentLinkedDeque class is similar, but additionally supports the Deque interface.
ConcurrentLinkedQueue类提供了一个高效、可扩展且线程安全的非阻塞FIFO队列。ConcurrentLinkedDeque类功能类似,但额外支持Deque接口。
Five implementations in java.util.concurrent support the extended BlockingQueue interface, that defines blocking versions of put and take: LinkedBlockingQueue, ArrayBlockingQueue, SynchronousQueue, PriorityBlockingQueue, and DelayQueue. The different classes cover the most common usage contexts for producer-consumer, messaging, parallel tasking, and related concurrent designs.
java.util.concurrent包中有五个类实现了扩展的BlockingQueue接口,该接口定义了阻塞版本的put和take方法:LinkedBlockingQueue、ArrayBlockingQueue、SynchronousQueue、PriorityBlockingQueue和DelayQueue。这些不同的类涵盖了生产者-消费者模式、消息传递、并行任务处理及相关并发设计中最常见的使用场景。
Extended interface TransferQueue, and implementation LinkedTransferQueue introduce a synchronous transfer method (along with related features) in which a producer may optionally block awaiting its consumer.
The BlockingDeque interface extends BlockingQueue to support both FIFO and LIFO (stack-based) operations. Class LinkedBlockingDeque provides an implementation.
Timing
The TimeUnit class provides multiple granularities (including nanoseconds) for specifying and controlling time-out based operations. Most classes in the package contain operations based on time-outs in addition to indefinite waits. In all cases that time-outs are used, the time-out specifies the minimum time that the method should wait before indicating that it timed-out. Implementations make a "best effort" to detect time-outs as soon as possible after they occur. However, an indefinite amount of time may elapse between a time-out being detected and a thread actually executing again after that time-out. All methods that accept timeout parameters treat values less than or equal to zero to mean not to wait at all. To wait "forever", you can use a value of Long.MAX_VALUE.
TimeUnit类提供了多种时间粒度(包括纳秒级)用于指定和控制基于超时的操作。该包中的大多数类除了支持无限期等待外,还包含基于超时的操作。在所有使用超时的情况下,超时时间表示该方法在报告超时前应等待的最短时间。实现会"尽最大努力"在超时发生后尽快检测到超时。然而,从检测到超时到线程实际恢复执行之间,可能会经过不确定的时间。所有接受超时参数的方法都将小于或等于零的值视为完全不等待。若要实现"永久"等待,可以使用Long.MAX_VALUE值。
Synchronizers
Five classes aid common special-purpose synchronization idioms.
- Semaphore is a classic concurrency tool.
- CountDownLatch is a very simple yet very common utility for blocking until a given number of signals, events, or conditions hold.
- A CyclicBarrier is a resettable multiway synchronization point useful in some styles of parallel programming.
- A Phaser provides a more flexible form of barrier that may be used to control phased computation among multiple threads.
- An Exchanger allows two threads to exchange objects at a rendezvous point, and is useful in several pipeline designs.
Concurrent Collections
Besides Queues, this package supplies Collection implementations designed for use in multithreaded contexts: ConcurrentHashMap, ConcurrentSkipListMap, ConcurrentSkipListSet, CopyOnWriteArrayList, and CopyOnWriteArraySet. When many threads are expected to access a given collection, a ConcurrentHashMap is normally preferable to a synchronized HashMap, and a ConcurrentSkipListMap is normally preferable to a synchronized TreeMap. A CopyOnWriteArrayList is preferable to a synchronized ArrayList when the expected number of reads and traversals greatly outnumber the number of updates to a list.
除队列外,该包还提供了专为多线程场景设计的集合实现:ConcurrentHashMap、ConcurrentSkipListMap、ConcurrentSkipListSet、CopyOnWriteArrayList和CopyOnWriteArraySet。当预期多个线程会访问同一个集合时,ConcurrentHashMap通常优于同步的HashMap,ConcurrentSkipListMap通常优于同步的TreeMap。当预期对列表的读取和遍历操作远多于更新操作时,CopyOnWriteArrayList优于同步的ArrayList。
The "Concurrent" prefix used with some classes in this package is a shorthand indicating several differences from similar "synchronized" classes. For example java.util.Hashtable and Collections.synchronizedMap(new HashMap()) are synchronized. But ConcurrentHashMap is "concurrent". A concurrent collection is thread-safe, but not governed by a single exclusion lock. In the particular case of ConcurrentHashMap, it safely permits any number of concurrent reads as well as a tunable number of concurrent writes. "Synchronized" classes can be useful when you need to prevent all access to a collection via a single lock, at the expense of poorer scalability. In other cases in which multiple threads are expected to access a common collection, "concurrent" versions are normally preferable. And unsynchronized collections are preferable when either collections are unshared, or are accessible only when holding other locks.
该包中某些类名前缀的"Concurrent"是一种简写形式,表示其与类似的"synchronized"类存在若干差异。例如java.util.Hashtable和Collections.synchronizedMap(new HashMap())属于同步类,而ConcurrentHashMap是"并发"类。并发集合是线程安全的,但不受单一互斥锁管控。以ConcurrentHashMap为例,它可安全支持任意数量的并发读取操作以及可调节数量的并发写入操作。当需要通过单一锁阻止所有集合访问时(可扩展性较差为代价),"同步"类较为适用。而在多线程需要访问公共集合的其他场景中,通常更推荐使用"并发"版本。当集合无需共享,或仅能在持有其他锁时访问的情况下,非同步集合则更为适宜。
Most concurrent Collection implementations (including most Queues) also differ from the usual java.util conventions in that their Iterators and Spliterators provide weakly consistent rather than fast-fail traversal:
大多数并发集合实现(包括大多数队列)也与常规的java.util约定不同,它们的迭代器和分割迭代器提供的是弱一致性而非快速失败的遍历:
- they may proceed concurrently with other operations
- they will never throw ConcurrentModificationException
- they are guaranteed to traverse elements as they existed upon construction exactly once, and may (but are not guaranteed to) reflect any modifications subsequent to construction.
Memory Consistency Properties
Chapter 17 of the Java Language Specification defines the happens-before relation on memory operations such as reads and writes of shared variables. The results of a write by one thread are guaranteed to be visible to a read by another thread only if the write operation happens-before the read operation. The synchronized and volatile constructs, as well as the Thread.start() and Thread.join() methods, can form happens-before relationships. In particular:
《Java语言规范》第17章定义了内存操作(如共享变量的读写)之间的happens-before关系。只有当写操作happens-before读操作时,才能保证一个线程的写操作结果对另一个线程的读操作可见。synchronized和volatile结构,以及Thread.start()和Thread.join()方法,都可以建立happens-before关系。具体而言:
- Each action in a thread happens-before every action in that thread that comes later in the program's order.
- An unlock (synchronized block or method exit) of a monitor happens-before every subsequent lock (synchronized block or method entry) of that same monitor. And because the happens-before relation is transitive, all actions of a thread prior to unlocking happen-before all actions subsequent to any thread locking that monitor.
- A write to a volatile field happens-before every subsequent read of that same field. Writes and reads of volatile fields have similar memory consistency effects as entering and exiting monitors, but do not entail mutual exclusion locking.
- A call to start on a thread happens-before any action in the started thread.
- All actions in a thread happen-before any other thread successfully returns from a join on that thread.
The methods of all classes in java.util.concurrent and its subpackages extend these guarantees to higher-level synchronization. In particular:
- Actions in a thread prior to placing an object into any concurrent collection happen-before actions subsequent to the access or removal of that element from the collection in another thread.
- Actions in a thread prior to the submission of a Runnable to an Executor happen-before its execution begins. Similarly for Callables submitted to an ExecutorService.
- Actions taken by the asynchronous computation represented by a Future happen-before actions subsequent to the retrieval of the result via Future.get() in another thread.
- Actions prior to "releasing" synchronizer methods such as Lock.unlock, Semaphore.release, and CountDownLatch.countDown happen-before actions subsequent to a successful "acquiring" method such as Lock.lock, Semaphore.acquire, Condition.await, and CountDownLatch.await on the same synchronizer object in another thread.
- For each pair of threads that successfully exchange objects via an Exchanger, actions prior to the exchange() in each thread happen-before those subsequent to the corresponding exchange() in another thread.
- Actions prior to calling CyclicBarrier.await and Phaser.awaitAdvance (as well as its variants) happen-before actions performed by the barrier action, and actions performed by the barrier action happen-before actions subsequent to a successful return from the corresponding await in other threads.
备注
FIFO —— first-in-first-out
1019

被折叠的 条评论
为什么被折叠?



