Java concurrency-Remembering the value deviation of statistical variables

Source: Internet
Author: User

1 Problem description

In a project, the results of the requests sent are counted, and the development colleague defines two global shared variables commonutil.reqfailnum and reqnum, each recording the number of failed requests and the number of requests sent. It is assumed that the request will handle failure before each request is sent, and that the number of failures is corrected until the 200 return code is successfully received.
Finally, when the application processing request is in a more frequent phase, there is a case where the reqfailnum is last reduced to a negative number, when a normal request is completed, Commonutil.reqfailnum + +; and commonutil.reqfailnum--should be paired up, This statistic value should not be negative.
The code to send the request is as follows:

private static Boolean Xmlpost (string content, String sendurl) throws Exception{boolean bn = False;if (null! = content) {//initial assumption request failed, wait for normal return 200 and then the number of failed records--commonutil.reqfailnum + +; URL URL =null; URLConnection con = null;outputstreamwriter out = null;try {url = new URL (sendurl); con = Url.openconnection ();} catch (Malformedurlexception E1) {throw new Connexception ("Malformedurlexception");} catch (IOException e) {throw new Con Nexception ("IOException");} Con.setconnecttimeout (con.setreadtimeout); Con.setdooutput (true); Con.setrequestproperty ("Connection" , "keep-alive"); Con.setrequestproperty ("Pragma:", "No-cache"); Con.setrequestproperty ("Cache-control", "No-cache") ; Con.setrequestproperty ("Content-type", "text/xml"); try {out = new OutputStreamWriter (Con.getoutputstream (), "UTF-8" ); Out.write (content); Out.flush (); Out.close ();} catch (Unsupportedencodingexception e) {throw new Connexception ("Unsupportedencodingexception");} catch (IOException E ) {String Exceptionstr = commonutil.stacktrAcestr (e); throw new Connexception ("IOException." +EXCEPTIONSTR);} Finally{try {if (out! = null) {Out.close ();}} catch (IOException e) {throw new Connexception ("IOException ...");} String headline = Con.getheaderfield (0); if (headline! = NULL && headline.indexof ("$") >-1) {COMMONUTIL.REQF Ailnum--; Commonutil.reqnum ++;bn = True;logger.info ("Sendurl:: Return + OK");}} return Bn;}
2 Error cause Analysis

Statistical variables in the concurrency environment, developers are ignoring their security issues. Because the method is called in action, the method is called for each request of the client. When the Web server processes the client's request, a thread is created for each request to process. This section of the statistical variable operation code, exposed in the multi-threaded environment, but there is no synchronization, it is easy to lead to inconsistent statistical data issues.
In this application, the reqfailnum++ operation should actually be an atomic operation, which contains three actions for memory "read-Modify-write", and the result state depends on the previous state. The above code, in the absence of synchronization, when two threads execute this line of code at the same time, it is possible to read the same value, while +1, the final should be two cumulative operation, the result is only one time, due to the loss of an incremental operation, the final statistical value of 1 deviation.
Since the + + code is the first few lines of the method, the probability of the thread executing the + + operation is large, while the commonutil.reqfailnum--; is executed after the successful processing of the request, which involves the network request, the processing time is more uncertain, so-the probability of the operation executing simultaneously is also low. The final reqfailnum++ will be lost more times than reqfailnum--lost, resulting in a negative value for the shared variable reqfailnum.

3 Solutions

1) Use the lock to place the reqfailnum++ or--operation in the synchronization code block
2) because it is a simple statistical variable, you can take advantage of the characteristics of the atom variable, using Atomicinteger or Atomiclong
Conclusion: In Web project, the thread security of shared variables is easy to be neglected, and the occurrence of data inconsistency problem has occasional, unpredictable and other factors (originally wanted to intercept a graph, but the application of the current concurrency is small, there is no data inconsistency phenomenon, this is the concurrency problem hidden and difficult to find the reason), in order to prevent , it is necessary to analyze the concurrency factors at the beginning of the project, so that developers can focus on the problem of variable state threading security.

Java concurrency-Remembering the value deviation of statistical variables

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.