Java program performance optimization: finding out the culprit of memory overflow and java Performance Optimization

Source: Internet
Author: User
Tags xms java se

Java program performance optimization: finding out the culprit of memory overflow and java Performance Optimization

I once worked on a small swing program when I first got into the line. I used java SE, swing, Thread, and other stuff. I didn't perform strict performance tests with little experience at the beginning, after a while in the production environment, I found that the applet sometimes throws java. lang. outOfMemoryError is abnormal, that is, java memory overflow. At that time, I also checked a lot of information on the Internet, tried some methods, and the code was slightly optimized, however, I still cannot find a solution. I don't know why java's garbage collection mechanism cannot recycle its resources after the sub-forms are closed, because this program may frequently switch some sub-forms, after these subforms are closed, the resource cannot be released, which may cause a potential risk of program OutOfMemoryError!

Recently, I accidentally saw JProbe, a tool used to monitor the memory usage of java programs, on the Internet. I immediately recalled the unsolved problem, so I downloaded JProbe8.0.0 and hoped to find the answer from the memory analysis. After the software is downloaded and installed, detailed user guides in the installation directory (people who know the software and English can get started quickly) are mainly involved in two steps:

1. use the JProbe Config tool to generate the control script for J2SE or J2EE programs (one. jpl file and. bat file) in the command line. directory where the bat file is located, and then execute the batch processing to run the java program to be monitored

2. run the JProbe Console tool and click "Attach to Session... "button to bring up the java program's real-time memory Monitoring Chart" Runtime Summary ". We mainly look at the content in the" Data "card (note: when you use the software for the first time, you may encounter some minor problems: for example, if a program published as a jar package reads the configuration file during running and starts from the control script, an exception may occur when the configuration file cannot be found. Solution: do not pack the jar package and publish it directly using the folder; the JProbe cannot be connected to the session of the control script because of some anti-virus software network firewalls, causing the monitoring chart to fail. The solution is to cancel the firewall's restrictions on JProbe access to the network)

Shows the Real-time Monitoring Chart "Runtime Summary:


You can set the packages or classes to be monitored, and click "Refresh Runtime Data" to Refresh the memory usage of these objects. If you think a class is suspicious, you can monitor the life cycle of a program and check whether the memory occupied after the life cycle ends as expected. As we all know, java memory is automatically recycled, which is called garbage collection without programmer intervention. This garbage collection may be irregular, when the program occupies a small amount of memory resources, the jvm garbage collection frequency may be relatively low. Otherwise, when the java program consumes a large amount of memory resources, the frequency and intensity of garbage collection are relatively high. The uncertainty of garbage collection may affect our judgment, however, you can click the "Request a Garbage Collection" button in the upper-right corner of the JProbe monitoring interface (like a recycle bin icon) to send a Garbage Collection Request to the jvm, wait a few seconds and then click "Refresh Runtime Data ", at this time, if the class name of the expected object has not been removed from the class column at the bottom of the monitoring interface or the number of objects has not been reduced (please try multiple times, you can include other operations that increase program memory usage to ensure that the jvm does perform garbage collection.) Congratulations! 90% possibility you have found a defect in the program

The process of finding the culprit may be quite time-consuming and a challenge to the programmer's patience. I spent one afternoon and one night, and I was very frustrated. Basically, I found and completed all the memory overflow vulnerabilities in my applet. The fact tells me that the root cause why the resource cannot be released after the subform is closed is that although the subform calls the dispose () method, the reference of the subform object is always in: it can be referenced by a static HashMap, its internal sub-Thread class is not released, or its event listening class is not released (by the eyes of JProbe, I found a lot of problems !), So. The key to completely releasing an object to occupy resources is to find and release all references to it!

The following are some of my experiences in solving specific problems:

HashMap, Hashtable, and other collection classes are most likely to cause memory overflow in the program, especially static ones. Be cautious !!! The referenced objects may have been destroyed. In fact, you may have forgotten the remove key value. If these collection objects are still statically attached to other classes, this reference may always be available. If you use JProbe to test it, the result is often unexpected. Solution: Delete the key, remove, and clear completely. If you allow this, set the set object to null.

For a thread object that is no longer used, if you want to completely kill it, the join method is recommended in many books. I did this before, however, with the help of the JProbe tool, I was surprised to find that the thread to be killed is still in your increasing memory, it is very likely that the join method will be a problem after the thread's sleep method is called. Solution: add a sentence before the join method to execute the interrupt method, but there may be new problems at this time: after the interrupt method is executed, your Thread class will throw InterruptedException, and there are countermeasures under the policy. You can perfect the solution by adding a switch variable for judgment. refer to the following code:

Java code
  1. /**
  2. * <P> Description: internal class of the Creation thread </p>
  3. * @ Author cuishen
  4. * @ Version 1.1
  5. */
  6. Class NewThread implements Runnable {
  7. Thread t;
  8. NewThread (){
  9. T = new Thread (this, path );
  10. T. start ();
  11. }
  12. Public void run (){
  13. Try {
  14. While (isThreadAlive ){
  15. StartMonitor ();
  16. Thread. sleep (Long. parseLong (controlList. get (controlList. size ()-1). toString ()));
  17. }
  18. } Catch (InterruptedException e ){
  19. If (! IfForceInterruptThread) {// switch variable
  20. StopThread (logThread );
  21. String error = "InterruptedException !!! "+ Path +": Interrupted. The thread is terminated abnormally! The program has tried to restart this thread !! ";
  22. System. err. println (error );
  23. LogService. writeLog (error );
  24. CreateLogThread ();
  25. }
  26. }
  27. }
  28. }
  29. Public void createLogThread (){
  30. IfForceInterruptThread = false; // switch variable
  31. LogThread = new NewThread ();
  32. }
  33. Private void stopThread (NewThread thread ){
  34. Try {
  35. Thread. t. join (1, 100 );
  36. } Catch (InterruptedException ex ){
  37. System. out. println ("An error occurred while terminating the thread !!! ");
  38. } Finally {
  39. Thread = null;
  40. }
  41. }
  42. /**
  43. * Method to close and completely release the thread Resource
  44. */
  45. Public void stopThread (){
  46. Try {
  47. IfForceInterruptThread = true; // switch variable
  48. IsThreadAlive = false;
  49. LogThread. t. interrupt ();
  50. LogThread. t. join (50 );
  51. } Catch (InterruptedException ex ){
  52. System. out. println ("An error occurred while terminating the thread !!! ");
  53. } Finally {
  54. This. controlList = null;
  55. This. keyList = null;
  56. LogThread = null;
  57. }
  58. }



For the form classes that inherit the JFrame, note that the following is added to the initialization method: this. setdefaclocloseoperation (DISPOSE_ON_CLOSE); and note that all the event Listening Classes associated with them are written as internal classes of the Form class. In this way, when the form dispose () is used, these internal classes are also destroyed, there will be no more inexplicable references.


General causes of memory overflow in java programs

The JVM memory is set to small or the data read at one time is too large, for example, list vertor

I. memory overflow type

1. java. lang. OutOfMemoryError: PermGen space

JVM manages two types of memory, heap and non-heap. Heap is used by developers. It is created at JVM startup. Non-heap is reserved for JVM and used to store class information. Unlike the heap, GC does not release space during runtime. If the web
The app uses a large number of third-party jar files or the application has too many class files, but the MaxPermSize setting is small. If it exceeds the upper limit, this memory will overoccupy and cause overflow, or during hot deployment of tomcat, the Environment loaded above will not be cleaned up, but the context will be changed to a new deployment, so there will be more and more non-heap content.

PermGen space stands for Permanent Generation.
Space refers to the permanent storage area of the memory. This memory is mainly used by JVM to store Class and Meta information. When the Class is loaded, it will be placed in PermGen.
In space, it is different from the Heap region of the storage Instance, GC (Garbage Collection) will not during the main program running period to PermGen
Therefore, if your application has a CLASS, the PermGen space error may occur. This error is often caused by the pre-processing of JSP on the web server.
Compile. If your web app uses a large number of third-party jar files and the size exceeds the default jvm size (4 MB), this error message is generated.

An example of the best configuration: (I have verified that tomcat has never died since I used this configuration)

Set JAVA_OPTS =-Xms800m-Xmx800m-XX: PermSize = 128 M-XX: MaxNewSize = 256 m
-XX: MaxPermSize = 256 m

2. java. lang. OutOfMemoryError: Java heap space

The first case is a supplement. The main problem is that it appears in this case. The default space (-Xms) is 1/64 of the physical memory, and the maximum space (-Xmx) is 1/4 of the physical memory. If the remaining memory is less than 40%, the JVM will increase the heap to the Xmx setting value. If the remaining memory exceeds 70%, the JVM will reduce the heap to the Xms setting value. Therefore, the Xmx and Xms settings of the server should be set to the same value to avoid adjusting the size of the VM heap after each GC operation. If the physical memory is infinitely large, the maximum JVM memory size is related to the operating system. Generally, 32-bit machines are between GB and 3 GB, and 64-bit machines are not limited.

Note: If the Xms value exceeds the Xmx value, or the sum of the heap maximum value and the non-heap maximum value exceeds the physical memory or the maximum operating system limit, the server cannot be started.

Garbage collection GC role

JVM calls GC frequently. Garbage collection is mainly performed in two cases:

When the application thread is idle, and when the java memory heap is insufficient, GC will be continuously called. If continuous collection fails to solve the problem of insufficient memory heap, the out
Memory error. This exception is determined by the system running environment, so it cannot be expected when it will appear.

According to the GC mechanism, program running may cause changes in the system runtime environment and increase the chance of GC triggering.

To avoid these problems, the program design and writing should avoid the memory usage and GC overhead of spam objects. It is shown that calling System. GC () can only be recommended that JVM recycle junk objects in memory, but not immediately,

One is that it cannot solve the problem of insufficient memory resources and increase GC consumption.

Ii. JVM memory zone Composition

Java stack and stack

Java divides memory into two types: stack memory and heap memory.

1. In the function, set... the remaining full text>
 
How can we quickly find out the cause of system memory overflow ??

You can take a look at the log to see what causes memory overflow, and then analyze the code to see if optimization can be performed.

Related Article

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.