Learn java-Counter-Revised version

Source: Internet
Author: User

Look directly at the code, the explanations are inside.

<%@ page language= "java" contenttype= "text/html; charset=utf-8"
pageencoding= "UTF-8"%>
<! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd"


<meta http-equiv= "Content-type" content= "text/html; charset=utf-8"
<title >insert title Here</title>

<body>
<%!//a synchronized lock
private static final OBJ  ECT lock = new Object ();%>
Hello word!
<%
Integer count = 0;
Is there a sync problem here?
//For example 2 users get the current counter at the same time,
//The number of visits plus 1
///When the update will lose the number of visits?
//
//Yes, you can add the following statement to the count= code to simulate it.
//So this is also to sync
//Then we define a sync lock, named Lock, placed in the static Code section of the JSP,
SYN Chronized (lock) {

//We use the Application Record page access counters
//Get data from inside
//Note This must be an integer instead of int
// For the first access, NULL is returned, and the NullPointerException
//
Count = (Integer) Application.getattribute is present when the integer is converted to int (" Index_couNTER ");

//
//Let thread wait 10 seconds, this is you can open 2 browsers, respectively refresh,
//Final counter is only increased by 1, rather than we expected 2
//Thread.Sleep (10000);

//If this is the first access, initialize
if (count = = null) {
//The Automatic box method supported by JDK5.0 is used here
Count = 0;
  
//Save to Application
Application.setattribute ("Index_counter", count);
}
count++;  
//Save to Application
Application.setattribute ("Index_counter", count);
}
%>

Current total number of visits is:<%=count%>

</body>

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.