Utilities in the Java. util. Concurrent package in JDK 6

Source: Internet
Author: User
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. Depending on the specific executor class used, it is possible that in the newly created thread, the existing task execution thread, orExecute ()And may be executed in sequence or concurrently.ExecutorServiceProvides multiple complete asynchronous task execution frameworks. Executorservice manages the queuing and arrangement of tasks and allows controlled shutdown.ScheduledExecutorServiceAdded support for delayed and scheduled task execution for subinterfaces and related interfaces. Executorservice provides a method for arranging asynchronous execution.CallableAny function. The result is similarRunnable.FutureReturns the result of the function, allows you to determine whether the execution is complete, and provides a method to cancel the execution.RunnableFutureYesRunMethod future,RunThe result is set when the method is executed.

.ClassThreadPoolExecutorAndScheduledThreadPoolExecutorProvides an adjustable and flexible thread pool.ExecutorsClass provides common types and configuration factory methods for most executors, and several utility methods for using them. Other executor-based utilities includeFutureTask, Which provides common extensible implementations of the future, andExecutorCompletionServiceIt helps coordinate the processing of asynchronous task groups.

Queue

Java. util. ConcurrentConcurrentLinkedQueueClass provides efficient, scalable, and thread-safe non-blocking FIFO queues. The five implementations in Java. util. Concurrent support extendedBlockingQueueInterface, which defines the blocking versions of put and take:LinkedBlockingQueue,ArrayBlockingQueue,SynchronousQueue,PriorityBlockingQueueAndDelayQueue. These classes cover most of the common use contexts of producer-user, message passing, parallel task execution, and related concurrency design.BlockingDequeInterface ExtensionBlockingqueueTo support FIFO and LIFO (stack-based) operations.LinkedBlockingDequeClass provides an implementation.

Timing

TimeUnitClass provides multiple granularities (including nanoseconds) for specifying and controlling timeout-based operations ). In addition to uncertain waiting, most classes in this package also contain timeout-based operations. In all cases where timeout is used, timeout specifies the minimum time that the method should wait before timeout. After the timeout occurs, the implementation will "try its best" to detect the timeout. However, it may take an uncertain time between the detection timeout and the actual execution thread again after the timeout. All methods that accept parameters over time 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.CountDownLatchIt is an extremely simple but extremely commonly used utility used to block execution before a certain number of signals, events, or conditions are maintained.CyclicBarrierIt is a retriable multi-channel synchronization point, which is useful in some parallel programming styles.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,CopyOnWriteArrayListAndCopyOnWriteArraySet. When many threads are expected to access a given collection,ConcurrenthashmapUsually better than synchronousHashmap,ConcurrentskiplistmapUsually better than synchronousTreemap. When the expected reading and traversal are much larger than the number of list updates,CopyonwritearraylistBetter than synchronousArraylist.

The "concurrent" prefix used with some classes in this package is short, indicating that it is different from a similar "synchronization" class. For example,Java. util. hashtableAndCollections. synchronizedmap (New hashmap ())Yes,ConcurrentHashMapIt is "concurrent ". Concurrent collection is thread-safe, but is not managed by a single exclusive lock. In this particular case, concurrenthashmap can securely allow any number of concurrent reads and write with an adjustable number. When you need to use a single lock to prohibit all access to the collection, the "synchronization" class is very useful at the cost of poor scalability. In other cases where multiple threads are expected to access the public collection, the "concurrent" version is usually better. If the collection is not shared, or the collection is accessible only when other locks are kept, non-synchronous 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.

Memory consistency attribute

Java language specification chapter 17th definesHappen-beforeLink. Only write operationsHappen-beforeRead Operations ensure that the results written by one thread are visible to the other.synchronizedAndvolatileStructureHappen-beforeLink,Thread.start()AndThread.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 becauseHappen-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 appliesExecutorServiceSubmitCallables.
  • Asynchronous computingFutureIndicates the action taken.Happen-beforeAnother threadFuture.get()Subsequent operations for obtaining results.
  • "Release" synchronous storage method (suchLock.unlock,Semaphore.releaseAndCountDownLatch.countDown) Previous operationsHappen-beforeIn the other line, the same synchronization storage object is successfully "obtained" (for exampleLock.lock,Semaphore.acquire,Condition.awaitAndCountDownLatch.await.
  • ForExchangerEach Thread Pair of the object is successfully exchanged.exchange()Previous operationsHappen-beforeCorrespondsexchange()Subsequent operations.
  • CallCyclicBarrier.awaitPrevious operationsHappen-beforeOperations performed by barrier operations and Barrier operationsHappen-beforeCorrespondsawaitSubsequent operations are returned successfully.
Related Article

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.