开发者

solution to memory leakage in this code [duplicate]

开发者 https://www.devze.com 2023-01-20 15:50 出处:网络
This question already has answers here: Closed 12 years ago. Possible Duplicate: does these code has memory leakage??
This question already has answers here: Closed 12 years ago.

Possible Duplicate:

does these code has memory leakage??

static private       ArrayList   seriesColors      = new ArrayList(); 

public Audiogram(int widthParm, int heightParm) 
            throws Exception 
    { 
        super(widthParm, heightParm); 
开发者_开发问答        seriesColors.add(new Color(  0,   0, 255)); 

        // Set the default settings to an industrial audiogram 
        setType(INDUSTRIAL_AUDIOGRAM); 
    } 

This piece of code causes memory leakage. What should be the change.

  1. Should i change the static variable into non static.

Generates audiogram graphs.

This class is mainly used to generate the standard audiogram XO graph.

The audiogram graph is normally displayed with the highest value at the bottom (i.e. -10 on top to 110 on the bottom) so that the line goes down as an employee's hearing gets worse.


Well, the only way this code could "leak" memory is if you just keep adding elements to seriesColors without ever removing any. So, to answer your question: Remove old / unnecessary colors from seriesColors or avoid adding them.

Regarding the static modifier: You should remove static in front of the seriesColors if you want each Audiogram to have its own instance of seriesColors. If you want the seriesColors to be shared among all instances of Audiogram then you should keep it static.


Audiogram is a constructor and seriesColors are not used apart from this method

Assuming that your statement is accurate, and assuming that you posted the entire constructor, the seriesColors attribute (static or not) serves no useful purpose whatsoever.

If this is the case, the then fix for the memory leak is to simply remove the seriesColors declaration from your code, as follows:

// static private ArrayList seriesColors = new ArrayList();  <<<=== remove this line

public Audiogram(int widthParm, int heightParm) 
        throws Exception 
{ 
    super(widthParm, heightParm); 
    // seriesColors.add(new Color(0, 0, 255)); <<<=== remove this line

    // Set the default settings to an industrial audiogram 
    setType(INDUSTRIAL_AUDIOGRAM); 
} 

However, I suspect that this is not the whole story ...

EDIT

Comment out those two lines as indicated. If the code compiles with those two lines commented out, then they are definitely redundant.

However, it strikes me that your knowledge of Java must be close to zero. If this is the case, you should NOT be trying to clean up memory leaks and the like in other peoples' code. Learn some Java first.

0

精彩评论

暂无评论...
验证码 换一张
取 消