I. Project BACKGROUND and issues
There is a self-adaptive Test learning system, the student's study requirements of the regular examination test, the student's results come out, the teacher will ask the system according to each student's examination paper on the wrong question from the capacity of the question from the bank of about ten million, Create an offline workbook for each student that has their own personalised review and practice. Therefore, every test, especially after the large test, the number of offline documents required to generate more, an examination of more than one person, on request to generate multiple documents.
The problem is that offline document generation is very slow and slow to what extent? An offline document generation average time in about two seconds, encountered poor grades of students, the content of the document is more, generated even takes 3 minutes, people, average three seconds, all generated, need 2000*45=90000 seconds, about a few hours. Why is it so slow? This is closely related to the generation of offline documents, for each topic from the database to save the question to find the title, the form of a single topic, the database stored in the form of HTML -like storage , for each topic, parsing the title text, Find the images that need to be downloaded, each topic contains a large or large number of images to download, wait until all the topics in the document download to the local completion, the entire document can continue processing.
TwoAnalysis and Improvement
The first version of the implementation, the server after receiving the teacher's request, will be the batch generation request decomposition into a separate task, and then complete the serial.
First, do service splitting:
The ability to generate offline documents has been removed as a separate service, provided externally RPC interface, after the WEB Server received the teacher's request for batch generation of offline documents, the request was split after one by one calls to the offline document generation RPC service, this RPC The service has a buffering mechanism at the time of implementation, caches the received requests, and quickly returns a result to the caller, so WEB The server can also quickly respond to a user's request.
Let's look at this offline document:
the creation of each document is very high, and is inherently suitable for multithreaded concurrency. So when the RPC service implementation, using the producer consumer model,RPC interface implementation received a caller's request, the request will be packaged into a container, and then there will be more than one thread to consume processing, That is, the generation of each specific document. Once the document is generated, the producer consumer mode is used once, another blocking queue is put in, and another set of threads is responsible for uploading. When the upload is completed successfully, the upload thread returns the document, indicating that the current document has completed successfully.
For each offline document generation itself:
Let's take a look at its business:
1, from the capacity of the question bank for each student to extract suitable for him,
2 , each topic contains a large number of images to be downloaded to the local, and the text part of the rendering. But when we look at the entire system, we will find that we are generating an adaptive workbook for the students after an exam, in other words, regardless of the content of the examination, the students ' grades, the knowledge points of each exam are limited, and the number of related topics that can be extracted from these points of knowledge is always limited. There is a great repetition of the topics that are needed between different students. For example, we for a student because of his mistakes in the examination paper part of The problem, there is a great probability that the other students and a student wrong place will be repeated, the corresponding topic will be repeated. For this part of the topic, we have absolutely no need to repeat the process, including retrieving the title from the database, parsing and downloading pictures. This is also a major breakthrough in optimization . Secondly , a workbook is composed of a number of topics, each of which is independent of each other, we can completely parallel, asynchronous processing each topic .
how exactly? ? To avoid duplication of effort:
map is certainly the most suitable, because we have to according to the topic of the to find the details of the topic, with which map concurrenthashmap
When the service receives a request to process a topic get Once, not found, Can think this is a new topic, ready to request the data from the database and the analysis of the problem, image download. There is a concurrency-safe point to note, because it is a multithreaded application, there will be multiple threads in the processing of multiple documents at the same time to deal with the same problem, this situation does not control, one will cause data conflicts and confusion, such as reading and writing the same disk file, the second is to cause the waste of computing resources, In order to prevent the document from being blocked on the current topic, the processing of each new topic is packaged as a callable Put a thread pool into it and treat the result as a future Return, wait until the thread is actually generating the document and then from the future get
If the topic is found in the cache , it is not a direct reference, because the problems in the question bank because of the possible changes in the relationship, such as the existence of errors, such as possible content is replaced, this time the cache data is actually expired, so need to check first. How to check? We said before the question bank on the average length in the size of about three bytes, directly equals to check whether the subject text has changed, the obvious efficiency is lower, so here another treatment, what treatment? A summary of SHA is made to the subject text in advance and saved in the database, and the question Bank development team is asked to make SHA abstracts when processing the problem data . In the local cache also saved this summary information, in the comparison of whether the change is outdated, first check whether the summary is consistent, summary of the topic does not need to update, the summary is inconsistent, only need to update the title text, this topic as a new topic, into the new topic of the process, so that the amount of data transmission reduction, It also reduces the pressure on the database.
This is only a partial optimization of the main code, note that the business scenario here is simulated, need to complete the code can go to my githup to get: Https://github.com/leeSmall/MultiThreadStudyDemo/tree/master /performanceoptimization
Before optimization:
PackageCom.study;ImportCom.study.aim.MakeSrcDoc;ImportCom.study.vo.PendingDocVo;ImportCom.study.aim.ProblemBank;ImportCom.study.service.DocService;Importjava.util.List;/*** * before optimization*/ Public classSingleweb { Public Static voidMain (string[] args) {System.out.println ("The question bank begins to initialize ..."); Problembank.initbank (); System.out.println ("The test bank initialization is complete. "); //the total document that needs to be generatedlist<pendingdocvo> docList = Makesrcdoc.makedoc (2); LongStarttotal =System.currenttimemillis (); for(PENDINGDOCVO doc:doclist) {System.out.println ("Start working on the document:" +doc.getdocname () + "..."); LongStart =System.currenttimemillis (); String LocalName=Docservice.makedoc (DOC); System.out.println ("Document" +localname+ "Generation Time:" + (System.currenttimemillis ()-start) + "MS"); Start=System.currenttimemillis (); String Remoteurl=Docservice.uploaddoc (LocalName); System.out.println ("uploaded to [" +remoteurl+ "] Time:" + (System.currenttimemillis ()-start) + "MS"); } System.out.println ("Total Time:" + (System.currenttimemillis ()-starttotal) + "MS"); }}
Generating 2 documents takes about 94 seconds
After optimization:
PackageCom.study.rpcmode;Importcom.study.aim.Consts;ImportCom.study.aim.MakeSrcDoc;ImportCom.study.aim.ProblemBank;ImportCom.study.service.DocService;ImportCom.study.vo.PendingDocVo;Importjava.util.List;Importjava.util.concurrent.*;/*** * After optimization: Service split, RPC service*/ Public classRpcmode {//generate a thread pool for a document Private StaticExecutorservice Docmakeservice= Executors.newfixedthreadpool (consts.thread_count_base*2); //thread pool for uploading documents Private StaticExecutorservice Docuploadservice= Executors.newfixedthreadpool (consts.thread_count_base*2); Private StaticCompletionservice Doccompletionservice=NewExecutorcompletionservice (Docmakeservice); Private StaticCompletionservice Uploadcompletionservice=NewExecutorcompletionservice (Docuploadservice); //Create a task for a single document Private Static classMakedoctaskImplementsCallable<string>{ PrivatePENDINGDOCVO PENDINGDOCVO; PublicMakedoctask (PENDINGDOCVO pendingdocvo) { This. PENDINGDOCVO =PENDINGDOCVO; } @Override PublicString Call ()throwsException {LongStart =System.currenttimemillis (); //a document is composed of a number of topics, each of which is independent of each other, so that each topic is processed in parallel and asynchronously. String LocalName =Docservice.makeasyn (PENDINGDOCVO); System.out.println ("Document" +localname+ "Generation Time:" + (System.currenttimemillis ()-start) + "MS"); returnLocalName; } } //tasks for uploading individual documents Private Static classUploaddoctaskImplementsCallable<string>{ PrivateString LocalName; PublicUploaddoctask (String localname) { This. LocalName =LocalName; } @Override PublicString Call ()throwsException {LongStart =System.currenttimemillis (); String Remoteurl=Docservice.uploaddoc (LocalName); System.out.println ("uploaded to [" +remoteurl+ "] Time:" + (System.currenttimemillis ()-start) + "MS"); returnRemoteurl; } } Public Static voidMain (string[] args)throwsinterruptedexception, executionexception {System.out.println ("The question bank begins to initialize ..."); Problembank.initbank (); System.out.println ("The test bank initialization is complete. "); //the total document that needs to be generatedlist<pendingdocvo> docList = Makesrcdoc.makedoc (2); LongStarttotal =System.currenttimemillis (); //The generation of each document is very independent, so the creation of the document is put into the thread pool to complete for(PENDINGDOCVO doc:doclist) {doccompletionservice.submit (NewMakedoctask (DOC)); } //The upload of each document is very independent, so the creation of the document is placed in the thread pool to complete for(PENDINGDOCVO doc:doclist) { future<String> Futurelocalname =Doccompletionservice.take (); Uploadcompletionservice.submit (NewUploaddoctask (Futurelocalname.get ())); } for(PENDINGDOCVO doc:doclist) {//get the uploaded network storage addressUploadcompletionservice.take (). get (); } System.out.println ("Total Time:" + (System.currenttimemillis ()-starttotal) + "MS"); }}
Generating 2 documents takes about 15 seconds
Third, continue to improve
First, there is the choice of the data structure:
Our careful analysis will find that as a long-running service, if we useConcurrenthashmap, which means that the memory footprint of the cache is growing over time. In the most extreme case, all 100,000 topics are loaded into memory, and how much memory will be occupied in this case? We do statistics, the average length of the questions in the -bytes or so, 100,000 topics are about to be used75Mabout the space. Looks good, but there are a few points, first, we in addition to the topic itself will have some other ancillary information needs to cache, such as the title picture in the local disk storage location and so on, that the actual cached data content will be far more than -bytes, two,MapThe type of memory usage efficiency is relatively low toHashMapFor example, memory utilization is typically only20%to the40%about, whileConcurrenthashmapwill only be lower, sometimes onlyHashMapof One-tenth to4which means that 100,000 of the topicsConcurrenthashmapwill actually occupy hundreds of trillion of memory space, it is very easy to cause memory overflow, that is, everyone commonOOM. Given this situation, we need a data structure that hasMapconvenient but can limit the memory footprint or you can refresh the cache according to a policy as needed. Finally, we choseConcurrentlinkedhashmap,this is byGoogleOpen Source A thread-safeHashMap, which itself is toConcurrenthashmapcan limit the maximum capacity and implement aLRUThat is, the least recently updated cache using algorithmic policies. Perfect fit our requirements, for the problem has been buffered, the less you can think of the topic from the current examination of the chapter farther away, the probability of being re-selected, the smaller the capacity is full, the need to make room for the new buffer, the less use will be priority to be cleared.
What happens after the service restarts?
Here we can also use local file storage in addition to the local memory cache, enabling a level two caching mechanism. Why use local file storage? In order to avoid this, the data that has been cached in memory is lost due to the fact that the server will be upgraded and will be down, and we have persisted the relevant data locally on the local disk.
Four, after the performance optimization to get the Enlightenment
What kind of revelation did the project's optimization bring to us?
Performance optimization must be based on in-depth analysis of the business, such as our performance optimization in the entry point, the choice of the cache data structure is based on the deep understanding of the business;
Performance optimization to be good at using the language of high concurrency characteristics, performance optimization of the use of caching, asynchronous tasks and other mechanisms, it is because we use these features and mechanisms, so that our application in the performance of a qualitative leap;
The introduction of various mechanisms should be taken into consideration to avoid the new security factors and bottlenecks, such as the expiration of the cache data, and the thread security problems in the concurrency, we need to overcome and solve.
Multi-threaded Series seven: Record a learning project performance optimization process and experience