The contents of the contract in Java

Source: Internet
Author: User

contents of concurrent packages in Java

1, Cyclicbarrier

A synchronization helper class that allows a group of threads to wait for each other until the set of threads reaches a common barrier point. The barrier can be reused after releasing the waiting thread, so it is called the barrier of the loop.

Here's an example:

  • Package test;


  • Import Java.util.concurrent.CyclicBarrier;

  • Import Java.util.concurrent.ExecutorService;

  • Import java.util.concurrent.Executors;


  • public class Recipes_cyclicbarrier {

  • public static Cyclicbarrier barrier = new Cyclicbarrier (10);


  • public static void Main (string[] args) {

  • Executorservice executor = Executors.newcachedthreadpool ();//fixedthreadpool (10);

  • for (int i=1;i<=10;i++) {

  • Executor.submit (New Thread (New Runner (i+ ")));

  • }

  • Executor.shutdown ();

  • }

  • }


  • Class Runner implements runnable{

  • private String name;


  • Public Runner (String name) {

  • THIS.name = name;

  • }


  • @Override

  • public void Run () {

  • SYSTEM.OUT.PRINTLN (name + "ready. ");

  • try {

  • Recipes_CyclicBarrier.barrier.await (); This is the public barrier point where all the waiting threads are freed after all threads have arrived.

  • } catch (Exception e) {

  • }

  • SYSTEM.OUT.PRINTLN (name + "Starting!") ");

  • }

  • }

  • 2, Countdownlatch

    Countdownlatch and Cyclicbarrier are a bit similar, but there are some differences. Countdownlatch is also a synchronous helper class that allows one or more threads to wait until an operation is completed in another thread. It is waiting for operations to be performed in other threads, and not between threads waiting for each other. Countdownlatch initialization requires a given count value, after each thread executes, the countdown () method must be called to reduce the count value by 1 until the count value is 0, at which time the waiting thread is freed.

    Here's an example:

    [Java] View plain copy

  • Package test;


  • Import Java.util.concurrent.CountDownLatch;

  • Import Java.util.concurrent.CyclicBarrier;

  • Import Java.util.concurrent.ExecutorService;

  • Import java.util.concurrent.Executors;


  • public class Countdownlatchdemo {

  • public static Countdownlatch Countdownlatch = new Countdownlatch (10);//Initialize Count value


  • public static void Main (string[] args) {

  • Executorservice executor = Executors.newcachedthreadpool ();//fixedthreadpool (10);

  • for (int i=1;i<=10;i++) {

  • Executor.submit (New Thread (New Runner1 (i+ ")));

  • }

  • Executor.shutdown ();

  • }

  • }


  • Class Runner1 implements runnable{

  • private String name;


  • Public Runner1 (String name) {

  • THIS.name = name;

  • }


  • @Override

  • public void Run () {

  • SYSTEM.OUT.PRINTLN (name + "ready. ");

  • CountDownLatchDemo.countDownLatch.countDown (); 1 reduction in count value

  • try {

  • CountDownLatchDemo.countDownLatch.await ();

  • } catch (Exception e) {

  • }

  • SYSTEM.OUT.PRINTLN (name + "Starting!") ");

  • }

  • }

  • 3, Copyonwritearraylist & Copyonwritearrayset

    Copyonwritearraylist & Copyonwritearrayset are concurrent containers that are suitable for reading and writing fewer scenes, such as the black-and-white list settings for websites. The disadvantage is the memory occupies big, the data consistency question, the Copyonwrite container only guarantees the data final consistency, cannot guarantee the data real-time consistency. Given these drawbacks, you can use the Concurrenthashmap container.

    Implementation principle: The data added to the container will be placed in a new container, then the original container reference to the new container, the old container will also exist, so there will be two containers occupy memory. We can also achieve our own copyonwritemap in the same way.

    4, Concurrenthashmap

    The Concurrenthashmap is also a concurrent container that minimizes the granularity of synchronization.

    Implementation principle: Concurrenthashmap By default is composed of 16 segment, each segment consists of multiple hashtable, the data changes need to go through two hashing algorithm, the first hash is positioned to segment, The second hash is anchored to the Hashtable under segment, and the container only locks a single segment and then operates Hashtable under segment, with multiple segment unaffected. If the need for expansion is not to segment expansion but to segment under the Hashtable expansion. Although the two-time hashing algorithm reduces efficiency, it is much more efficient than locking the entire container.

    5, Blockingqueue

    Blockingqueue is just an interface, its implementation class has Arrayblockingqueue, Linkedblockingqueue, Priorityblockingqueue, Synchronousqueue, Delayqueue, Linkedblockingdeque.

    Arrayblockingqueue: Bounded blocking queue supported by data.

    Linkedblockingqueue: A blocking queue based on a link node and an arbitrary range.

    Priorityblockingqueue: Unbounded blocking queue.

    Synchronousqueue: A blocking queue in which each insert operation must wait for the corresponding removal from another thread.

    A unbounded blocking queue for the delayqueue:delayed element.

    Linkedblockingdeque: You can add and remove elements at both ends of a queue, based on a linked node and an arbitrary range of double-ended blocking queues.

    6. Lock

    Lock is divided into fair and non-fair locks, the default is the non-fair lock. Implementation classes have Reetrantlock, Reetrantreadwritelock, and are dependent on Abstractqueuedsynchronizer abstract classes. Reetrantlock the operation of all lock interfaces to the Sync class, Sync has two subclasses: Nonfairsync and Faisync, which can be known to handle both unfair and fair locks, respectively. Abstractqueuedsynchronizer all requests into a CLH queue, here is a virtual queue, when the thread is competing for a lock, the line routines first attempt to acquire the lock, which is not fair for the threads waiting in the queue. If the thread is running, it is added to the tail of the queue through a cyclic CAS operation until it is added successfully.

    7. Atomic Bag

    The classes under the atomic package implement atomic operations with classes that implement atomic operations on basic types such as int, Long, and Boolean: Atomicinteger, Atomiclong, Atomicboolean, if an object needs to be atomically manipulated, There are also atomicreference classes for atomic manipulation of object references, as well as atomic classes for manipulating object arrays: Atomicintegerarray, Atomiclongarray, Atomicreferencearray. The core idea of atomic operations is CAS operations, which are then invoked by the underlying operating system directives.



The contents of the contract in Java

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.