Java. util. Concurrent Chinese API

Source: Internet
Author: User
 

Overview   Software Package  Class Use  Tree  Expired  Index  Help 
Javatm Platform
Standard ed. 6
 Previous Software PackageNext package

 

Software Package java. util. Concurrent

A common Utility Class for concurrent programming.

 

See:
Description

 

Interface Abstract
Blockingdeque <E>

Supports two additional operations
QueueThe two operations are as follows:

Empty; When storing elements, wait for the space in the double-end queue to become available.

Blockingqueue <E>

Supports two additional operations
QueueThe two operations are: Wait for the queue to become non-empty when getting elements,

And wait for the space to become available when storing elements.

Callable <v> A task that returns results and may throw exceptions.
Completionservice <v> Services that separate the production of new asynchronous tasks from those that use the results of completed tasks.
Concurrentmap <K, V> Provide other atomsPutifabsent,Remove,ReplaceMethod
Map.
Concurrentnavigablemap <K, V>

Supported
NavigableMapOperation, and supports its navigation sub- ing recursively

ConcurrentMap.

Delayed A hybrid interface used to mark objects that should be executed after a given delay time.
Executor Execute submitted
RunnableTask object.
Executorservice

ExecutorProvides methods for managing termination and tracking the execution status of one or more asynchronous tasks.

Generate
Future.

Future <v> FutureThe result of asynchronous calculation.
Rejectedexecutionhandler Failed
ThreadPoolExecutorThe processing program of the executed task.
Runnablefuture <v> As
RunnableOf
Future.
Runnablescheduledfuture <v> As
RunnableOf
ScheduledFuture.
Scheduledexecutorservice One
ExecutorServiceWhich can be scheduled to run or periodically run after a given delay.
Scheduledfuture <v> A delayed and acceptable result operation can be canceled.
Threadfactory Create a new thread object as needed.

 

Class Abstract
Abstractexecutorservice Provide
ExecutorServiceThe default Implementation of the execution method.
Arrayblockingqueue <E> A Bounded blocking queue supported by arrays.
Concurrenthashmap <K, V> The hash table that supports obtaining full concurrency and updating the expected adjustable concurrency.
Concurrent1_queue <E> A connection node-based unbounded thread security queue.
Concurrentskiplistmap <K, V> Scalable concurrency
ConcurrentNavigableMap.
Concurrentskiplistset <E>

A
ConcurrentSkipListMapZooming concurrency

NavigableSet.

Copyonwritearraylist <E>

ArrayListIs a thread-safe variant, where all variable operations (Add,Set

And so on) are implemented by performing a new copy on the underlying array.

Copyonwritearrayset <E> Use internal
CopyOnWriteArrayListOf
Set.
Countdownlatch

A synchronization helper class that allows

One or more threads are waiting.

Cyclicbarrier

A synchronization helper class that allows a group of threads to wait for each other until it reaches a public barrier.

Point (common barrier point ).

Delayqueue <E extends delayed>

DelayedAn unbounded blocking queue of an element, which can be extracted only when the delay expires.

Element.

Exchanger <v> The synchronization point of the thread in which the elements can be paired and exchanged.
Executorcompletionservice <v> Use provided
ExecutorTo execute the task
CompletionService.
Executors

The
Executor,ExecutorService,

ScheduledExecutorService,ThreadFactory
And
Callable

Class factory and practical methods.

Futuretask <v> Cancelable asynchronous computing.
Linkedblockingdeque <E> A blocked dual-end Queue Based on connected nodes in any range.
Linkedblockingqueue <E> A node with any range based on connected nodes
Blocking queue.
Priorityblockingqueue <E>

An unbounded blocking queue, Which is used with the class

PriorityQueueSame sequence rules

And provides the blocking access operation.

Scheduledthreadpoolexecutor

ThreadPoolExecutorIt can run the command after the specified delay separately,

Or regularly execute commands.

Semaphore A count semaphore.
Synchronousqueue <E>

One blocking queue, where each insert operation must wait for the corresponding removal operation of another thread

And vice versa.

Threadpoolexecutor

One
ExecutorServiceIt uses one of several possible pool threads to execute each

The submitted task, usually used
ExecutorsFactory method configuration.

Threadpoolexecutor. abortpolicy

The handler used for the rejected task. It will throw

Rejectedexecutionexception.

Threadpoolexecutor. callerrunspolicy

The handler used for the rejected task.ExecuteIn the call thread of the Method

A rejected task is run. If the execution program is closed, the task is discarded.

Threadpoolexecutor. discardoldestpolicy

The handler used for the rejected task. It discards the oldest unprocessed request and then tries again.

ExecuteIf the execution program is closed, the task is discarded.

Threadpoolexecutor. discardpolicy The processing program used for a rejected task. By default, the rejected task is discarded.

 

Enumeration Summary
Timeunit

TimeunitIndicates the time period of a given unit granularity. It provides cross-unit conversion and timing and latency operations in these units.

Utility method.

 

Exception Summary
Brokenbarrierexception

When a thread tries to wait for a broken barrier, or the barrier enters the disconnected state

This exception is thrown when the process is in the waiting state.

Cancellationexception

If a value is used to generate a task (for example
FutureTask).

This exception is thrown.

Executionexception This exception is thrown when you try to obtain the result of a task that has been aborted by throwing an exception.
Rejectedexecutionexception When a task cannot be executed
ExecutorThe exception thrown.
Timeoutexception This exception is thrown when the blocking operation times out.

Description of the software package java. util. Concurrent

 

A common Utility Class for concurrent programming. This package includes several small, standardized and scalable frameworks, and some classes that provide useful functions.

. The main components are briefly described below. For more information, seeLocksAndAtomicPackage.

Execution Program
  • Interface

    ExecutorIs a simple standardized interface used to define custom subsystems similar to threads, including thread pools, asynchronous Io, and lightweight task frameworks. Root

    Depending on the specific executor class used, it may be in the newly created thread, the existing task execution thread, orExecute ()In the thread

    Execute tasks in sequence or concurrently.ExecutorServiceProvides multiple complete asynchronous task execution frameworks. Executorservice Management

    Tasks are queued and arranged, and controlled shutdown is allowed.ScheduledExecutorServiceAdded latency and scheduled tasks for sub-interfaces and related interfaces.

    Service Execution Support. Executorservice provides a method for arranging asynchronous execution.
    CallableAny function. The result is similar

    Runnable.FutureReturns the result of the function, allows you to determine whether the execution is complete, and provides a method to cancel the execution.RunnableFuture
    YesRun

    Method future,RunThe result is set when the method is executed.

     

  • Implementation

    Class
    ThreadPoolExecutorAnd
    ScheduledThreadPoolExecutorProvides an adjustable and flexible thread pool.ExecutorsMost classes are provided

    Common types and configuration factory methods of executors, and several utility methods for using them. Other executor-based utilities include

    Body Type
    FutureTask, Which provides common extensible implementations of the future, and
    ExecutorCompletionServiceIt helps to coordinate asynchronous tasks

    The processing of the Service Group.

    Queue

    Java. util. Concurrent
    ConcurrentLinkedQueueClass provides efficient, scalable, and thread-safe non-blocking FIFO queues.

    The five implementations in Java. util. Concurrent support extended
    BlockingQueueInterface, which defines the blocking versions of put and take:

    LinkedBlockingQueue,ArrayBlockingQueue,SynchronousQueue,PriorityBlockingQueue
    And

    DelayQueue. These classes cover most of the Common Use Cases of producer-user, message passing, parallel task execution, and related concurrency design.

    Text.BlockingDequeInterface Extension
    BlockingqueueTo support FIFO and LIFO (stack-based) operations.LinkedBlockingDeque

    Class provides an implementation.

    Timing

    TimeUnitClass provides multiple granularities (including nanoseconds) for specifying and controlling timeout-based operations ). Most classes in this package contain uncertain waits

    Besides, timeout-based operations are also included. In all cases where timeout is used, timeout specifies the minimum time that the method should wait before timeout. Sending upon timeout

    After being generated, the implementation will "try its best" to detect timeout. However, it may take an uncertain time between the detection timeout and the actual execution thread again after the timeout. Accept timeout

    All methods of phase parameters are considered as not waiting for values smaller than or equal to 0. To "always" wait, you can useLong. max_valueValue.

    Synx

    The four types can help implement common dedicated synchronization statements.SemaphoreIs a classic concurrency tool.CountDownLatch
    Is extremely simple but extremely

    A common utility used to block execution before a specified number of signals, events, or conditions are maintained.CyclicBarrierIs a reset multi-channel synchronization point, in

    Some parallel programming styles are useful.ExchangerTwo threads are allowed to exchange objects at collection points, which is useful in Multi-pipeline design.

    Concurrent collection

    In addition to queues, this package also provides collection implementation designed for multi-threaded context:ConcurrentHashMap,

    ConcurrentSkipListMap,ConcurrentSkipListSet,CopyOnWriteArrayList
    And
    CopyOnWriteArraySet. Current Period

    When many threads access a given collection,ConcurrenthashmapUsually better than synchronousHashmap,Concurrentskiplistmap

    Usually better than synchronousTreemap. When the expected reading and traversal are much larger than the number of list updates,CopyonwritearraylistBetter than synchronous

    Arraylist.

     

    The "concurrent & rdquo prefix; used with some classes in this package is a short form, indicating that it is different from a similar" synchronization "class. For example,

    Java. util. hashtableAndCollections. synchronizedmap (New hashmap ())Yes,

    ConcurrentHashMap

    It is "concurrent ". Concurrent collection is thread-safe, but is not managed by a single exclusive lock. In the specific situation of concurrenthashmap

    It can securely allow any number of concurrent reads and write with an adjustable number. You must use a single lock to disallow all

    During access, the "synchronization" class is very useful, and its cost is poor scalability. In other cases where multiple threads are expected to access the public collection

    "Concurrent" versions should be better. If the collection is not shared, or the collection is accessible only when other locks are kept, it is not synchronized.

    Collection is better.

     

    Most concurrent collection implementations (including most Queue) are different from conventional java. util conventions because their iterators provideWeak ConsistentInstead of traversing a fast failure. The Weak Consistent iterator is thread-safe, but there is no need to freeze the collection during iteration, so it does not necessarily reflect all updates since the iterator was created.

    Java language specification chapter 17th defines
    Happen-beforeLink. Only write operationsHappen-beforeRead Operations ensure that the results written by one thread are visible to the other.synchronizedAnd
    volatileStructureHappen-beforeLink,Thread.start()And
    Thread.join()
    Method FormationHappen-beforeLink. Especially:

    • Every operation in the threadHappen-beforeEach operation in the thread that will be passed in program order later.
    • An unlock Monitor (synchronizedBlocking or method Exit)Happen-beforeEach subsequent lock of the same Monitor (synchronizedBlocking or method access ). And because
      Happen-beforeLinks can be passed, so all operations on the previous thread are unlocked.Happen-beforeLock all subsequent operations of any thread of the monitor.
    • WritevolatileFieldHappen-beforeEach subsequent read of the same field.volatileThe reading and writing of fields have similar memory consistency effects with the entry and exit of the monitor,NoMutex lock is required.
    • Call on Threadstart Happen-beforeAny thread in the started thread.
    • All operations in the threadHappen-beforeFrom this threadjoinAny other threads returned successfully.

    java.util.concurrentAnd its sub-packages extend these guarantees for higher-level synchronization. Especially:

    • Operations before putting an object into any concurrent collection in a threadHappen-beforeSubsequent operations to access or remove this element from collections in another thread.
    • Thread directionExecutorSubmitRunnablePrevious operationsHappen-beforeThe execution starts. The same applies
      ExecutorServiceSubmitCallables.
    • Asynchronous computingFutureIndicates the action taken.Happen-beforeAnother threadFuture.get()Subsequent operations for obtaining results.
    • "Release" synchronous storage method (suchLock.unlock,Semaphore.releaseAnd
      CountDownLatch.countDown
      ) Previous operationsHappen-beforeIn the other line, the same synchronization storage object is successfully "obtained" (for example
      Lock.lock,Semaphore.acquire,Condition.awaitAnd
      CountDownLatch.await.
    • ForExchangerEach Thread Pair of the object is successfully exchanged.exchange()Previous operations
      Happen-before
      Correspondsexchange()Subsequent operations.
    • CallCyclicBarrier.awaitPrevious operationsHappen-beforeOperations performed by barrier operations and Barrier operations
      Happen-beforeCorrespondsawaitSubsequent operations are returned successfully.

     

     

    Start with the following versions:
    1.5

    Overview   Software Package  Class Use  Tree  Expired  Index  Help 
    Javatm Platform
    Standard ed. 6
     Previous Software PackageNext package

     

     

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.