Java performance exploration

xiaoxiao2021-03-06  57

During the development of www.jobcn.com, there have been some problems when they run, and I will make a summary of my problem solution for future references. And please don't worry. Question 1: Resin's database connection is growing in the program operation, the last connection number exceeds the maximum number, causing the RESIN service Closing reason: After the database is completed, the database connection is not closed; or return the result set (ResultSet) without closing the database connection in JSP. Solution: 1. Turn off the database connection in the operation of the database. 2. Try not to return the result set ResultSet, you can return to the Vector, a "multiple fields), which can close the database in the JavaBean. 3. If the result set is returned in the JavaBean, you can also write a ConnectDB (Connect Database), ClosedB (Close Database), and then call connectDb (), establish a database connection, and create a database connection, and you can create a database connection. Operation, the operation database is completed, and the database can be turned off via CloseDB (). 4. Try to use conn.close (), rs.close (), rs.close () when close the connection, do not write it to close it, such as call DB.CloseConnection (conn), etc., this is actually impact on performance. Because this performance has passed my test for a single file. 5. Please do sequentially when you turn it off, such as rs.close () .., stmt.close () .. conn.close () .... problem 2 : When running a JSP program, RESIN has grown up, and it is high. Eventually resin is insufficient, even when it is machine. Cause: Excessive memory.

Solution: 1. Since the amount of data is relatively large, use to make a string connection, and I believe that everyone is very familiar with String, and we often use it to make a string connection, for example: String A = B C File: // b, C is string but is this in the actual compilation: string a = new stringbuffer (). Append (b) .append (c) .tostring () obviously in a simple In the statement, there is more than 2 objects: .StringBuffer (). Tostring Returns a string. We compare the performance of these two programs: Script 1: StringBuffer s = new stringBuffer (); long start = system. CurrentTimeMillis (); for (INT i = 0; I <10000; i ) {S1 = "a";} long stop = system.currenttimemillis (); system.out.println (stop-start); program block 2: StringBuffer s = new stringbuffer (10000); // long start = system.currenttimemillis (); for (int i = 0; i <10000; i ) {S.Append ("a");} long stop = system.currentTimeMillis ); System.out.println (stop-start); Compare the result, the gap is obvious. As for why String connection is done, because String cannot directly change its length, but must use StringBuffer usage. It is therefore recommended to use the StringBuffer Append method to connect to the string. 2. When I solve this problem, I also try to use the above method, the effect is not very obvious (consuming memory). Later, when you display a lot of data, avoid the steps connected to the string, and use out.println () and direct output. Question 3: Java does not prevent the program to occupy too much memory. When the object is insufficient to the memory, the garbage collector will automatically start, release the memory occupied by the reference number as zero, Java does not automatically release the use of useless objects. If the program forgot to release the reference to the object, the memory time is increased while the program is incremented, and the so-called memory leak will, but create an object not only consumes the CPU. Time and memory, while the Garbage Collector is kept constantly to release the object memory JVM, which will also consume a lot of CPU time. Workaround: Because Running a JSP program, Resin's memory will have a slow growth, which will also cause memory overflow, in order to avoid this presence, the final solution is to write a servlet program, start on When the server is time, start a servlet, run every 20 minutes to run once, and reclaim memory. Question 4: The debugging information in the log file is not comment. Workaround: After the program is passed, try to remove the debug information. At the same time, you must write the program name when you capture the error, easy to find. Question 5 improve performance and increase the speed.

Specific example: Let's take a look at the code snippet for the Vector class: for (int i = 0; i If V contains 100,000 elements, this code snippet will call the v.size () method 100,000 times. Although the Size method is a simple Method, but it still needs a way to call overhead. At least JVM needs to configure and clear the stack environment. Here, the code inside the for loop does not modify the size of the Vector Type Object V in any way, so the above code is best Record into this form:

INT size = v.size (); for (int i = 0; i

Although this is a simple change, it still has won performance. After all, every CPU cycle is precious.

Question 6: Don't write <% @ page import = "java.lang. *"%> In the JSP file.

Because Java does not need to introduce this package, you can reference the class files in it.

Question 7: Use Vector HashTable to return a query result resulset.

Workaround: Recording Set: Place a record in a HashTable, then put it again

Add to Vector, loop record the result set, return to Vector

Some of the code of the Java file behind it (not including the connection and close of the database)

Package com.jobcn.company;

/ **********************************************************

***** Description:

***** Recording set: A record is placed in a HashTable, then put it again

Put it in the vector, loop record the result set, return to Vector

*************************************************** /

Import java.io. *;

Import java.sql. *;

Import java.util. *;

Import java.text. *;

PUBLIC CLASS HASHTABLE_VECTOR_RS

{

/ * ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ---------------- * /

/ * Function Name: GetMultirowInfo

/ * Function Description: Return the recordset, put it in Hashtable

/ * Parameters: SQL statement, field number

/ * Return Value: Success --- Htable, Failure --- NULL

/ * ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ---------------- * /

Public Vector ListResult (String SqlStatement, Int Num)

{

Vector Listrs = new vector ();

Try

{

Connectdb ();

RS = stmt.executequery (SQLStatement);

// Judgment field data type

// Date type back 93

// INT returns 2, 4

// Bigint type returns 3

// String type returns 12

// (CHAR type) Returns 1

INT T = -1;

RSMD = rs.getMetAdata ();

INT columncount = 0;

IF (Num> 0)

Columncount = NUM;

Else

Columncount = rsmd.getcolumncount ();

While (rs.next ())

{

Hashtable htable = new hashtable (); for (int i = 1; i <= columncount; i )

{

T = rsmd.getColumnPe (i);

System.out.println ("i =" i ", t =" t "name =" rsmd.getColumnname (i));

IF (t == 12 || T == 1 || T == 3)

{

IF (rs.getstring (i) == null || rs.getstring (i) .equals ("))

HTable.PUT (RSMD.GetColumnname (i), "");

Else

HTable.Put (RSMD.GetColumnname (i), RS.GetString (i));

}

ELSE IF (t == 93)

{

HTable.Put (RSMD.GetColumnName (i), RS.Getdate (i) .tostring ());

}

Else IF (t == 2 || t == 4)

{

HTable.Put (RSMD.GetColumnName (i), Integer.Tostring (Rs.Getint (i))));

}

}

Listrs.add (htable);

} // e

Return Listrs;

}

Catch (Exception Listerror)

{

System.out.println ("Database Operation Failed!" Listerror);

Return NULL;

}

Finally

{

Try

{

Closedb ();

}

Catch (Exception Closeerr)

{

System.out.println ("Close Database error:" Closeerr);

}

}

}

}

Question 8: JSP program also has a designed place for, for example, select a drop-down box, submit it once, list the selected data, select another drop-down box, listen to the selected data again.

Solution:

Try to choose the condition, then list the selected data, and when the data is more, try to use the page, reduce the runtime.

Question 9: Performance optimization, try to use PreparedStatement

Solution:

The PreparedStatement object and the common statement object used are different.

First, they are for performance and compiled by JDBC drivers or databases (precompiled).

Second, they accept one or more dynamic input parameters called IN parameters. These two points allow the PreparedStatement object to be used for duplicate SQL operations, where the operation is basically the same, only minute differences (such as data load). To make the SQL statement is ready before use, you must transfer SQL to the JDBC driver when it is created, not when it is executed.

The in parameter is represented in SQL STRING? Before the PreparedStatement can successfully execute, the setxxx () method of the preparedStatement object must be called to set the IN parameter, and the data type of the parameter of XXX is set here is replaced. Thus, set the first IN parameter to an integer value 100, you should call Setint (1, 100). Similarly, set the second IN parameter as a string value "RJB", you should call SetString (2, "RJB"). The last point is that the set parameter value is set to a new value, or it will remain the same before clearparameters () explicitly. This is important because preparedStatement can be executed multiple times; if you don't pay attention, you will make your database full of useless data. Question 10: 1, put the unused JSP files.

Question 11: Submit the page, each time you submit twice. the reason:

1,

Here if Type = "sbumit", the page will be submitted twice, (this BUG believes that everyone knows that there is no need to come out)

The Submit button will be submitted once in the OnClick event.

Solution:

If the page is submitted in the onclick event, the type TYPE of the button must not be a "submit or image" button.

Can be "button".

Solution:

Go out

The statement.

Question 13: When you jump to another page, you have to add Return. Doing so may cause errors. Jump does not. IF {

Request.getRequestDispatcher ("/ xxx / errorpage.jsp? s_mark = error: Record Have Existed"). Forward (Request, Response);

Return;

}

Else

{

Response.sendredirect ();

// Recommended the above method

Return;

}

-------------------------------------------------- -----------------------------------------------

Reposted: SNOW Date: 2004-09-14

转载请注明原文地址:https://www.9cbs.com/read-117068.html

New Post(0)