Java underlying problem----There is a memory leak in Java, please briefly describe

Source: Internet
Author: User
Tags garbage collection int size modifiers static class stub tomcat
A memory leak means that an object or variable that is no longer being used by a program is occupied in memory. Java has a garbage collection mechanism that ensures that an object is no longer referenced, that is, when an object becomes orphaned, and the object is automatically purged from memory by the garbage collector. Because Java uses a graph-like approach to garbage collection management, you can eliminate the problem of reference loops, such as having two objects, referencing each other, so long as they are not up to the root process, and the GC can recycle them, for example, the following code can see the memory recycle:
Package Com.huawei.interview;

Import java.io.IOException;

public class Garbagetest {

/**
* @param args
* @throws IOException
*/
public static void Main (string[] args) throws IOException {
TODO auto-generated Method Stub
try {
Gctest ();
catch (IOException e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
System.out.println ("has exited gctest!");
System.in.read ();
System.in.read ();
SYSTEM.OUT.PRINTLN ("Out begin gc!");
for (int i=0;i<100;i++)
{
System.GC ();
System.in.read ();
System.in.read ();
}
}

private static void Gctest () throws IOException {
System.in.read ();
System.in.read ();
person P1 = new person ();
System.in.read ();
System.in.read ();
person P2 = new person ();
P1.setmate (p2);
P2.setmate (p1);
System.out.println ("Before exit gctest!");
System.in.read ();
System.in.read ();
System.GC ();
System.out.println ("Exit gctest!");
}

private Static class person
{
byte[] data = new byte[20000000];
person mate = null;
public void Setmate
{
mate = Other;
}
}
}

Memory leaks in Java: A long lifecycle object holds a reference to a short lifecycle object and is likely to have a memory leak, although the short lifecycle object is no longer needed, but because the long lifecycle object holds its reference and cannot be reclaimed, this is the scenario where memory leaks occur in Java, and in layman's sense, Is that the programmer may have created an object, this object is not used in the future, the object has been referenced, that the object is useless but can not be reclaimed by the garbage collector, this is the case of memory leaks in Java, for example, the caching system, we loaded an object in the cache ( For example, in a global map object, and then never use it, the object has been cached for reference, but is no longer used.
Check the memory leak in Java, be sure to let the program to complete the various branches of the end of the program, and then see whether an object has been used, if not, you can determine that the object belongs to the memory leak.

If the method of an instance object of an external class returns an instance object of an inner class, this internal class object is long referenced, even if the external class instance object is no longer in use, but the external class object will not be garbage collected because of the inner class persistence of the instance object of the outer class, which can also cause memory leaks.

The following is from the Internet (the main feature is to empty the stack of an element, instead of taking it out of the array altogether, but reducing the total number of stores, I can write better than this, and when I take off an element, let it disappear from the array and set the value of the location of that element to null:
I can't imagine a more classic example than that. so that I have to cite other people's examples, the following example is not what I think, is read in the book, of course, if not seen in the book, may be a period of time I also want to, but at that time I said it was my own thought and no one believed.


public class Stack {
Private object[] Elements=new object[10];
private int size = 0;
public void push (Object e) {
Ensurecapacity ();
elements[size++] = e;
}
Public Object pop () {
if (size = = 0)


throw new Emptystackexception ();
return elements[--size];
}
private void Ensurecapacity () {
if (elements.length = = size) {
object[] oldelements = elements;
elements = new object[2 * Elements.length+1];
System.arraycopy (oldelements,0, elements, 0, size);
}
}
}
The above principle should be very simple, if the stack adds 10 elements, and then all bounce out, although the stack is empty, there is nothing we want, but this is an object can not be recycled, this is in line with the memory leak of the two conditions: useless, can not be recycled.


But the existence of such things will not necessarily lead to what kind of consequences, if the stack used less, but also wasted a few k memory, anyway, our memory on the G, where will have any impact, and then this thing will soon be recycled, what is the relationship. Here's a look at two examples.


Example 1
public class bad{
public static Stack S=stack ();
static{
S.push (New Object ());
S.pop (); Here's an object that has a memory leak.
S.push (New Object ()); The object above can be recycled, which is equivalent to healing.
}
}
Because it's static, it's always there for the program to quit, but we can also see that it has self-healing capabilities, that is, if your stack has up to 100 objects, then up to 100 objects will not be recycled. In fact, this should be easy to understand, stack internal hold 100 references, The worst case scenario is that they are useless, because once we put in a new spirit, the previous references naturally disappear.



Another scenario for memory leaks: When an object is stored in the HashSet collection, it is not possible to modify those fields in the object that participate in the computed hash, otherwise the modified hash value of the object is different from the hash value originally stored in the HashSet collection, in which case Even if the Contains method retrieves an object in the HashSet collection using the current reference of the object as an argument, the result of the object cannot be found, which also causes the memory leak to be unable to delete the current object individually from the HashSet collection.



71, can you write a class, also called Java.lang.String.



Can, but in the application, the need to use their own class loader to load, otherwise, the system's ClassLoader will always just load the Jre.jar package in the java.lang.String. Because in Tomcat Web applications, the classes in the Web-inf/classess directory are loaded by WebApp's own classloader before they are delegated to the class loader of the parent. If we write a java.lang.String in Tomcat's Web application, the servlet program loads the java.lang.String that we write ourselves, but there are a lot of potential problems with this, and all the java.lang.String classes The problem will occur.

Although Java provides endorsed technology, you can overwrite certain classes in the JDK, specifically ... However, the classes that can be overridden are scoped, excluding classes in packages such as Java.lang.

(for example, the main reason is to learn to understand only use, not as part of the answer, otherwise, people suspected that the topic leaked) For example, run the following program:
Package Java.lang;

public class String {

/**
* @param args
*/
public static void Main (string[] args) {
TODO auto-generated Method Stub
System.out.println ("string");
}

}
The error reported is as follows:
Java.lang.NoSuchMethodError:main
Exception in thread "main"
This is because the java.lang.String with the JRE is loaded, and there is no main method in the class.

A. Java code error Checking


1.
Abstract class Name {
private String name;
Public abstract Boolean Isstupidname (String name) {}
}
Heroes, what's wrong with that?
Answer: wrong. Abstract method must end with a semicolon with no curly braces.
2.
public class Something {
void DoSomething () {
Private String s = "";
int L = s.length ();
}
}
Is it wrong?
Answer: wrong. You cannot place any access modifiers (private,public, and protected) before a local variable. Final can be used to modify local variables
(final, like abstract and STRICTFP, are non-access modifiers, STRICTFP can only modify class and method rather than variable).
3.
Abstract class Something {
Private abstract String dosomething ();
}
There seems to be nothing wrong with that, right?
Answer: wrong. The methods of abstract cannot be decorated with private. Abstract methods is to let subclass implement (achieve) specific details, how can use private to abstract
method to seal it up? (Similarly, abstract method cannot be added before final).
4.
public class Something {
public int AddOne (final int x) {
return ++x;
}
}
This is more obvious.
Answer: wrong. int x is modified to final, meaning that x cannot be modified in AddOne method.
5.
public class Something {
public static void Main (string[] args) {
Other o = new Other ();
New something (). AddOne (o);
}
public void AddOne (final other O) {
o.i++;
}
}
Class Other {
public int i;
}
Similar to the above, is the final question, is this wrong?
Answer: Right. In AddOne method, the parameter o is decorated to final. If we modify the reference of O in AddOne method
(for example: o = new Other ();), so it is wrong to do so as in the previous example. But the modified here is O's member vairable
(member variable), and O's reference does not change.
6.
Class Something {
int i;
public void dosomething () {
System.out.println ("i =" + i);
}
}
What's wrong with it? I can't see it.
Answer: Right. The output is "i = 0". int I belongs to instant variable (instance variable, or called member variable). Instant variable has default value. The default value of int is 0.
7.
Class Something {
final int i;
public void dosomething () {
System.out.println ("i =" + i);
}
}
There is only one place different from the one above, that is, one more final. Is that a mistake?
Answer: wrong. Final int i is a final instant variable (instance variable, or called member variable). The final instant variable does not have default value and must be given a definite value before the end of the constructor (constructor). Can be modified to "final int i = 0;".
8.
public class Something {
public static void Main (string[] args) {
Something s = new Something ();
System.out.println ("s.dosomething () returns" + dosomething ());
}
Public String dosomething () {
Return ' do something ... ';
}
}
It looks perfect.
Answer: wrong. It looks like there's nothing wrong with call dosomething in Main, after all, two methods are in the same class. But look closely, main is static. Static method cannot directly call non-static methods. Can be changed to "System.out.println (" s.dosomething () returns "+ s.dosomething ());". Similarly, static method cannot access non-static instant variable.
9.
Here, the something class file is named Otherthing.java
Class Something {
private static void Main (string[] something_to_do) {
System.out.println ("Do something ...");
}
}
This seems to be obvious.
Answer: Right. No one has ever said that the Java class name must be the same as its filename. But the name of the public class must be the same as the file name.
10.
Interface a{
int x = 0;
}
Class b{
int x = 1;
}
Class C extends B implements A {
public void PX () {
SYSTEM.OUT.PRINTLN (x);
}
public static void Main (string[] args) {
New C (). PX ();
}
}
Answer: wrong. An error occurs at compile time (error description different JVM has different information, meaning ambiguous x calls, two x matches (just like declaring date directly when you import Java.util and java.sql two packages at the same time). For variables of the parent class, you can use Super.x to specify that the properties of the interface are implicitly public static final by default. So you can make it clear by a.x.
11.
Interface Playable {
void Play ();
}
Interface Bounceable {
void Play ();
}
Interface Rollable extends playable, bounceable {
Ball Ball = new Ball ("Pingpang");
}
Class Ball implements rollable {
private String name;
Public String GetName () {
return name;
}
Public Ball (String name) {
THIS.name = name;
}
public void Play () {
Ball = new Ball ("Football");
System.out.println (Ball.getname ());
}
}
This mistake is not easy to find.
Answer: wrong. "Interface Rollable extends playable, bounceable" no problem. Interface can inherit multiple interfaces, so this is true. The problem is in the interface rollable "Ball Ball = new Ball (" Pingpang ");". Any interface variable (interface variable, also known as a member variable) declared in interface, is public static final by default. That is to say "Ball Ball = new Ball" ("Pingpang"); is actually "public static final Ball Ball = new Ball (" Pingpang ");". In the play () method of the ball class, "ball = new Ball (" Football ");" Changed the reference of ball, and here ball from rollable interface,rollable interface is public and final, The final object cannot be changed reference. The compiler will therefore be in the "ball = new Ball (" Football "); This shows the error.
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.