Java concurrent programming and java concurrency

Source: Internet
Author: User

Java concurrent programming and java concurrency

The reason why Latch and Barrier are put together is that they give people a similar feeling.
They all block some behaviors until an event occurs, but Latch is waiting for an event, while Barrier is waiting for the thread.


First, compare the descriptions of the two in JCIP:
Latch-A latch is a synchronizer that can delay the progress of threads until it reaches its terminal state. A latch acts as a gate: until the latch reaches the terminal state the gate is closed and no thread can pass, and in the terminal state the gate opens, allowing all threads to pass. once the latch reaches the terminal state, it cannot change state again, so it remains open forever. latches Can be used to ensure that certain activities do not proceed until other one-time activities complete.
That is, locking can delay thread execution until it reaches the corresponding end state. Locking is like a door. failing to reach the end state is equivalent to closing the door and preventing any thread from passing through.
When the end state is reached, the door is open to allow all threads to pass, but it will not be closed once it is opened.
Blocking can be used to ensure that some activities are executed after an event occurs.

 

Barrier-inform icbarrier allows a fixed number of parties to rendezvous limit at a barrier point and is useful in parallel iterative algorithms that break down a problem into fixa ed number of independent subproblems. threads call await when they reach the barrier point, and await blocks until all the threads have reached the barrier point. if all threads meet at the barrier point, the barrier has been successfully passed, in which case all threads are released and the barrier is reset so it can be used again.
Many people translate Barrier into a "Barrier". I also like this.
A fence enables a group to be executed in one place. That is to say, we can use a fence to break down a problem into multiple independent sub-problems and merge them at the same place after execution.
When the thread reaches the collection location and calls await, The await method will be blocked until other threads reach the collection location.
If all threads arrive, they can be released through the barrier, that is, all threads, and the barrier can be reused.


In addition, the differences between the two are described in javadoc below:
A CountDownLatch is initialized with a given count. the await methods block until the current count reaches zero due to invocations of the countDown method, after which all waiting threads are released and any subsequent invocations of await return immediately. this is a one-shot phenomenon -- the count cannot be reset. if you need a version that resets the count, consider using a packet icbarrier.
Blocking is always triggered by events.
The await method will be blocked until the countDown method changes the number of times to 0, and all threads can be released for subsequent work.
However, this phenomenon can only occur once, that is, the number of triggers will not be reset.
If you want a locks that can be reset, use a fence.

Another typical usage wocould be to divide a problem into N parts, describe each part with a Runnable that executes that portion and counts down on the latch, and queue all the Runnables to an Executor. when all sub-parts are complete, the coordinating thread will be able to pass through await. (When threads must repeatedly count down in this way, instead use a transaction icbarrier .)
One of the typical usage of this behavior blocking is to divide a problem into multiple parts, each part is responsible for different threads, and remember to reduce the number of lock settings.
When all threads are finished, the await method will cause blocking. If we need to do this repeatedly, we need to use the fence.


Well, since Mr. Doug Lea has elaborated on the same point of view so many times, the rest is to use it with confidence. Maybe we have thought the problem too complicated.
The following shows the example. One startGate stops the execution of all threads. When all threads are ready, countDown is called to release them, and the other one is waiting for the execution time of the endGate, the events that endGate waits for are triggered by these threads:

public class TestHarness {        public static long timeTasks(int nThreads, final Runnable task)                throws InterruptedException {            final CountDownLatch startGate = new CountDownLatch(1);            final CountDownLatch endGate = new CountDownLatch(nThreads);             for (int i = 0; i < nThreads; i++) {                Thread t = new Thread() {                    public void run() {                        try {                            startGate.await();                            try {                                task.run();                            } finally {                                endGate.countDown();                            }                        } catch (InterruptedException ignored) {                        }                    }                };                t.start();            }             long start = System.nanoTime();            startGate.countDown();            endGate.await();            long end = System.nanoTime();            return end - start;        }}

 

Run the following command:

public static void main(String[] args) throws ExecutionException, InterruptedException {        System.out.println("cost :::"+TestHarness.timeTasks(10,new Runnable() {            @Override            public void run() {                int num = RandomUtils.nextInt(0,100);                if(num>50) try {                    Thread.sleep(1000);                } catch (InterruptedException e) {                    e.printStackTrace();                }                System.out.println("Alvez ::"+ num);            }        }));    }

 

Next, try the barrier without any complicated things. Pay attention to countSupposed % partyCount, mainly to see if the barrier can be used multiple times.
If the countSupposed % partyCount result is exactly 0, the main thread ends normally after all threads finish execution.
Otherwise, it will be blocked. If the countSupposed % partyCount result is greater than 1 and not 0, then we can see "let's go to the barrier !! "Number of occurrences:

public static void barrierTest(int partyCount, int countSupposed) {     if(partyCount<1 || countSupposed < 1) throw new IllegalArgumentException();    final CyclicBarrier barrier = new CyclicBarrier(partyCount,new Runnable() {        @Override        public void run() {            System.out.println("let's go barrier !!");        }    });    System.out.println(countSupposed%partyCount==0?"let's show the smooth!!":"....but blocked");    for (int i = 0; i < countSupposed; i++) {        Runnable runnable = new Runnable() {            @Override            public void run() {                try {                    barrier.await();                    System.out.println(Thread.currentThread().getName() + " show!!");                } catch (InterruptedException e) {                    e.printStackTrace();                } catch (BrokenBarrierException e) {                    e.printStackTrace();                }            }        };        new Thread(runnable).start();    } }

 

Run:

public static void main(String[] args) {        barrierTest(11, 20);}

 


JAVA concurrent programming practices

I don't want to continue with the translation. It is indeed difficult to understand some words, but as far as the content is concerned, this book should be regarded as a pearl in the JAVA concurrency field, the path to concurrency is shown in the light. (If you have the ability to read the English version, since you have to talk about the Chinese version, it is better to talk about it, at that time, I felt that when I was reading this book, I used a new idiom to describe it-it was not clear. In the past two years, concurrency has become popular. In fact, it has been popular for decades, it can be responsibly said that almost all of the Chinese characters you can see on the Internet about JAVA concurrency can be found in this book. I personally think we should introduce JMM, which can at least bring up a lot of interest. The translation of this book is obscure. It is not a level problem if you try to understand it without a hard head, it is hard to imagine that it took 10 hours to complete the book again. In fact, after reading this book, you should be able to understand the concurrent libraries and frameworks in the JAVA field that are currently quite awesome. Of course, you will also be particularly careful with the use of locks, release visibility, activity, performance, and testing. This book covers a wide range of contents, and cannot be completely digested at once. The example is representative and targeted. It is worth reading this book again when you face concurrency, if there are not many contacts or you just know about concurrency, it is also very suitable for you to have a good understanding of the concurrency field in the JAVA World, and you will have a better understanding of the re-reading. JAVA concurrency is really amazing, it cannot be described as powerful and flexible. Of course, this power is costly. I personally think that after reading this, I should read the concurrent library in JDK carefully. Although this book is about JAVA concurrency, if you have other language experience, you should also recommend reading this book, so that you can understand the JAVA World's concurrency is so wonderful and complicated. Although the details in the book cannot be fully remembered, it is enough to create an index. You can read it again later.

JAVA concurrent programming practices

I don't want to continue with the translation. It is indeed difficult to understand some words, but as far as the content is concerned, this book should be regarded as a pearl in the JAVA concurrency field, the path to concurrency is shown in the light. (If you have the ability to read the English version, since you have to talk about the Chinese version, it is better to talk about it, at that time, I felt that when I was reading this book, I used a new idiom to describe it-it was not clear. In the past two years, concurrency has become popular. In fact, it has been popular for decades, it can be responsibly said that almost all of the Chinese characters you can see on the Internet about JAVA concurrency can be found in this book. I personally think we should introduce JMM, which can at least bring up a lot of interest. The translation of this book is obscure. It is not a level problem if you try to understand it without a hard head, it is hard to imagine that it took 10 hours to complete the book again. In fact, after reading this book, you should be able to understand the concurrent libraries and frameworks in the JAVA field that are currently quite awesome. Of course, you will also be particularly careful with the use of locks, release visibility, activity, performance, and testing. This book covers a wide range of contents, and cannot be completely digested at once. The example is representative and targeted. It is worth reading this book again when you face concurrency, if there are not many contacts or you just know about concurrency, it is also very suitable for you to have a good understanding of the concurrency field in the JAVA World, and you will have a better understanding of the re-reading. JAVA concurrency is really amazing, it cannot be described as powerful and flexible. Of course, this power is costly. I personally think that after reading this, I should read the concurrent library in JDK carefully. Although this book is about JAVA concurrency, if you have other language experience, you should also recommend reading this book, so that you can understand the JAVA World's concurrency is so wonderful and complicated. Although the details in the book cannot be fully remembered, it is enough to create an index. You can read it again later.

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.