The use, learning and testing of multithreading concurrency

Source: Internet
Author: User
Tags semaphore

Use

Let's talk about the use of multithreading. Multithreading itself is inseparable from the development of our projects, as long as we provide an interface, then he may be multiple threads simultaneously call, will produce concurrency problems, so developers in the actual development of multi-threaded understanding is crucial. Of course, this is the most basic understanding.

In this respect, for developers and students who have studied concurrency, the main requirements for development are:

1. First, the most involved. When you see static modified variables, you can think of multi-threaded resource sharing. If it is mutable, you need to be aware of the thread safety in change, and if it is immutable, you need to know how to make it immutable, rather than simply put it there, and the current code does not modify him to think he is unchanged.

2. When you see final, Singleton, and other definitions, you can analyze whether it is thread-safe.

3. When you see the results of collections, maps, and so on, know which classes are better suited, and when to use concurrent classes, and when to use ordinary classes, there is essentially an understanding of thread closure.

4. Be aware of the associated concurrency risk points when encountering classes that are not secure by thread such as SimpleDateFormat

5. When you need to do some big tasks, know how to speed up with a thread pool, and some thread scheduling with AQS related components

6. Know the common thread safety methods, can analyze the situation according to the need to lock to ensure thread safety.

Speaking so much, I believe many people have been able to feel the concurrency in the daily development of the existence, but also can be more understanding of concurrency. While you may find it difficult to use concurrency, you need to know if there is a problem with the code you see, and concurrency issues are more in the details of the process. This is also a lot of students asked me why not a course on the nature of concurrent combat, but rather choose according to the knowledge points in the course of explaining the use of some of their scenarios. At the same time, because of the number of concurrent knowledge points and complex, a single course of several scenes difficult to cover the entire concurrency knowledge system, this will lead to a lot of people to learn the concurrency is still the same as before, but to consolidate the knowledge point, others ask the heart is still very empty. Furthermore, if some knowledge points of concurrency are deliberately used in certain scenes in order to cover the knowledge points, they may cause many misunderstandings, but the effect is not necessarily satisfactory.

Continue to talk about the use of multithreading. Described earlier is the multi-threading we have to deal with, and then introduce the use of actively created multithreading, that is, we actively use multithreading in the code to deal with some business.

1. Speed up, take full advantage of the CPU: this should be easier to understand, the same task, multiple threads at the same time, so that a lot of processing parallel to achieve faster completion. Here is a scene, before the project big release, to clean the historical data (for example, to take a row based on the ID, and calculate a value to fill in), because of the large amount of data, single-threaded cleaning may take about 1 hours, in order to complete as soon as possible, does not affect the release time, so we changed the single thread to 10 The test found that 10 threads were still somewhat slow, then adjusted to 20 threads at the same time, which eventually completed around 3min.

2. Spin down and coordinate the use of resources: as soon as we finish the speed-up, it is said that spin down, many people may be very strange. Here is a concrete example to illustrate, such as the project to send text messages, there is a third-party limit is the concurrency of up to 10, and the peak time of the day to send the same time the amount of text messages may be much higher than 10, then how to do it? In the text message can be introduced into the thread pool and multithreaded processing, Through the semaphore and other control simultaneously texting thread not more than 10, so it played a role of spin down.

3. Asynchronous processing, decoupling. Usually when we are doing a business implementation, there are main processes and sub-process points, such as when our user orders, but also to complete the record core log (the core log may be recorded in the database) and notify the user to complete the non-core business, such non-core business in the processing, sometimes can be time-consuming, What is wrong can not let the main process fail, the error will need to retry the slow completion, this will open a new thread to handle, asynchronous decoupling, so that the main process quickly completed and returned. Of course, there is no limit to open new threads, put online constructor control better.

Many people do not know how to use multi-threading, I hope this summary can let you deepen your understanding. About the use of multithreading, in what scenarios should not use what scenario should not be used back down, but the need for the actual scene analysis, whether it is necessary to speed up, slow down, asynchronous processing, so that in the work of good use of multithreading.

Learn

Prior to the interview in the preparation and study of the problem of concurrency, here do not do too much to explain, do a simple summary:

  

Or in the course of this picture, this picture is not simply covering the concurrency of knowledge points, but I hope you can put this picture in the mind. When you tell someone about concurrency, you can describe several big aspects of concurrency first, and then you can refine them in one big way. This is also a good way to learn concurrency, the mind has this diagram, you can quickly put the knowledge point over again, which knowledge points blurred you can go to supplement it, and not every time you need to learn concurrency is from the beginning, and every time you read it feels almost what.

This method is also particularly suitable for use in interviews. Interviewer to let you talk about the concurrency of understanding, you can summarize the whole and then the local refinement, will let you in this link greatly add points. Many students have benefited from it and hope this will help you. Of course, this first overall summary and then the local refinement of the way, also suitable for everyone to learn other aspects of knowledge, will make your memory more profound, follow-up consolidation is also easy to many.

Test

The use and learning of concurrency, followed by validation, also belongs to concurrent testing. Concurrent tests can typically be verified by interfaces and methods in two directions, and can be selected according to different needs.

First say according to the interface test. This is usually with tools, Postman, JMeter, Apache Bench (AB), etc. are good choices, where JMeter, Apache Bench (AB) is more suitable for testers to use, Postman more suitable for developers to use.

Besides, test by method. Method test is better suited to writing code to test, here is a template:

public class Concurrencytest {

Total number of requests

public static int clienttotal = 5000;

Number of concurrently executing threads

public static int threadtotal = 200;

public static void Main (string[] args) throws Exception {

Executorservice Executorservice = Executors.newcachedthreadpool ();

Final semaphoresemaphore = new Semaphore (threadtotal);

Final countdownlatchcountdownlatch = new Countdownlatch (clienttotal);

for (int i = 0; I clienttotal; i++) {

Executorservice.execute (()-{

try {

Semaphore.acquire ();

TestMethod ();

Semaphore.release ();

} catch (Exception e) {

Log.error (Exception, E);

}

Countdownlatch.countdown ();

});

}

Countdownlatch.await ();

Executorservice.shutdown ();

Parts of all threads that can be executed before they are executed

}

private static void TestMethod () {

Methods to be validated

}

}

TestMethod This method is replaced by the method to be tested. If you do not need to execute some code on all threads, you can remove the use of Countdownlatch, and if you do not need to control the number of simultaneous threads at the same time, you can remove the use of semaphore.

Here by the way, to add a trick, sometimes in order to make the test results more obvious, the TestMethod method can be considered by the Thread.Sleep method to make the test method to perform slower, so that the results of the concurrency test more significant.

It is also hoped that in the actual project, especially the distributed system concurrency scenario, the core point should have the value of the core variable of the log record. But do not use System.out to output the log, and we usually discuss the slf4j, Logback, and so on, is recommended, because they will include in our analysis can use: thread name, line of code, and the time of the output log, etc. System.out not only does not have this important information, but also uses the synchronized at the output, which leads directly to the thread blocking in the output log. More

In the actual project, especially in the distributed system, many problems of analysis, we have to rely on the project during the operation of the output of the log. Thread name, code line, output log time, related variable value these are the most critical in the analysis process, I hope you can attract attention.

  

?

The use, learning and testing of multithreading concurrency

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.