Helping out the Garbage Collector

Hey, need a bit of advice:
I'm working on an app which is doing a particular task every so often. Left to its own devices, the memory size of the application quickly baloons up to around 300,000k before settling in. However, if I start each iterator with a System.gc(), the memory consumption is a more manageable 80,000k. However, running gc so much really sucks down the cpu and causes everything to go slowly. Anybody have any suggestions about how I can help java clean up better?
Thanks

maybe GC is convienent, but someitmes I like to be a control freak.
anyway, for the benefit of the community... It appears that cleaning up a StringBuilding is easier than cleaning up a string. i.e.
StringBuilder results = new StringBuilder();
                       while ((line = reader.readLine()) != null) {
                            if (line.equals(commEscape)) {
                                 parseResults(results.toString(), node);
                                 return;
                            results.append(line);
                            results.append("\n");
                       }cleans up much nicer (i.e. doesn't baloon up to 300M) than
String results = ""
                       while ((line = reader.readLine()) != null) {
                            if (line.equals(commEscape)) {
                                 parseResults(results.toString(), node);
                                 return;
                                results += line + "\n";
                       }at least in my application :)
I wonder why that is?

Similar Messages

  • How to get the garbage collector to work?

    Hi,
    i have i program where i load an image scale it down and save the scaled version in an array. I do this for a whole directory of images.
    After every image i set the temporary variable for the loaded image = null and call the function System.gc().
    My problem is, that the garbage collector does�nt give the memory of the loaded image free and the used memory of my program grows with every loaded image.
    /* Reads all images from a folder an stores them in an Array of images */
         public static BufferedImage[] readScaledImagesFromFolder(String folder,
                   int maxSize) {
              File dir = new File(folder);     /* Open the Folder */
              String[] children = dir.list();          /* Get the children of the folder */
              if (children == null) {
                 // Either dir does not exist or is not a directory
                  System.out.println("No images in the folder!");
                  return null;
             } else {
                  /* Init array for images */
                  BufferedImage[] images = new BufferedImage[children.length];     
                  int i = 0;
                  int index = 0;
                  BufferedImage temp;
                  String filename, fileending;
                 for (i=0; i<children.length; i++) {
                      // Get filename of file or directory
                     filename = children;
         /* Get the fileending of the file */
         fileending = filename.toLowerCase().substring(filename.length()-4);
         if(fileending.equals(".jpg") || fileending.equals(".bmp")
                   || fileending.equals(".png") || fileending.equals(".gif"))
              /* Read the image */
              temp = util.ImageUtils.loadBufferedImage(folder+"/"+filename);
              /* Scale the image down and save it in an array */
              images[index] = Util.getScaledImage(temp,maxSize);
              index++;          
         temp = null;
         System.gc();
         Mosaic.sourceImageNum = index;
         System.out.println((index+1)+" resized pictures loaded from folder: "+folder);
         return images;     
    How can i get the gargabe collector to work after every iteration?
    I tried to let the Thread.sleep(10) after System.gc() but it does�nt help.
    Thank you every much
    JackNeil

    Hm yes.. i now that System.gc() is only a
    suggestion.
    But i know what my program is doing and that it
    does�nt need the temporary image anymore after i have
    a scaled down version. And the temporay image will become unreachable as soon as reading the next one overwrites your temp variable. Setting the variable to null doesn't have much effect.
    It would be smarter to load the new image over the
    old temporary image and not to expand the heapsize to
    maximum.Then look at the possibitly of loading the next image into the same bufferedimage.

  • Swing components and the garbage collector

    How much care does one need to take with swing components, with reference to running out of stack space? I ask because I'm writing a system for an automotive parts company, and the company tends to not reboot the machines very often...
    Anyway... if a JFrame is closed, is it and all its components marked for GCing? Do I need to call the dispose method, or is this part of the default close behaviour? Or is there something else entirely?
    Cheers

    In class that calls for .setVisible(false) of one JFrame u MUST call
    for dispose() method.
    so
    myFrame.setVisible(false)
    myFrame.dispose()
    myFrame = null // to help the garbage collector
    If u have classes that becames from JFrame (or JDialog) u can
    invoke in its constructors:
    this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE)
    This makes uncecessary to call for dispose() method explicetly.
    If u do not have this kind of classes u can invoke this method
    after u have create your JFrame
    JFrame myFrame = new JFrame();
    myFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE)
    The most important thing is REMOVE ALL LISETNERS that u have added, so, if u have classes that becames from JFrame u can ovverride
    the dispose method to do that
    eg
    public void dispose()
    super.dispose()
    removeActionListener(.....)
    and so on
    If u do not have this kind of classes u must remove all listeners u have
    added before u invoke the setVisible(false) method.
    Regards

  • How intelligent is the garbage collector?

    Hi all,
    I've got a question about how garbage collection works in an ABAP objects context.
    If there are no more references an object is cleaned up and the memory released. Fine.
    What about an object O1, which in turn creates another object O2. O2 however also contains a refernce to O1.
    When the original process completes, this leaves two objects that reference each other, but with no other contact to the 'outside world'. Is the garbage collector intelligent enough to dump them?
    Any input appreciated,
    Cheers
    Mike

    Hi,
    Thanks for the feedback. I am still not sure - you say 'when the program ends it's part'. This is exactly the point - when the program ends, do the objects remain because they still contain references to each other?
    More detail:
    The references are public instance attributes of both objects (different classes). I would prefer to use functional methods, but am stuck with public attributes which I'm populating in the constructor.
    So a process P declares a local var LV_O1 and does a CREATE OBJECT LV_O1.
    In the constructor of O1, it does a
    CREATE OBJECT me->ATTR_O2 to populate it's attribute with a reference to an instance of O2.
    O2 doesn't need to do a CREATE OBJECT, but assigns a ref to O1 to it's attribute ATTR_O1.
    So now O1 and O2 refer to each other by public attributes:
    O1->ATTR_O2 and O2->ATTR_O1.
    The big question is what happens when process P ends and it's variable LV_O1 ceases to exist?
    In case anyone's wondering about the overall wisdom of the design, they have to be public attributes (used in Workflow) and they have to refer to each other as instantiation may also happen the other way around.
    Cheers
    Mike

  • Is it possible to disable the garbage collector?

    I was just wondering if it's possible to disable the garbage collector... Thank you.

    Try running with the -Xnoclassgc parameter.
    http://java.sun.com/developer/JDCTechTips/2004/tt0420.html#2

  • How does the Garbage Collector handle reference-free objects?

    Hi,
    I am interested to know how the GC handle's objects created
    without a reference.
    The reason this has become of interest to me is that I have
    created a "Title" class. The Title class animates each letter of
    Title.text to appear in a cloud of smoke.
    The smoke is a simple particle system class, when a particle
    dies it removes it's associated MovieClip so that eventually all
    MovieClip's have been destroyed.
    Now in the Title class for each letter I do the following
    (psuedo-code):
    for( Title.text.length) {
    CurrentLetter.twAlpha = new Tween( blah, blah, blah); //
    object created
    with a reference
    new Smoke( CurrentLetter.x, CurrentLetter.y); // object
    created
    without a reference
    Although this is technique is not one I would ever have
    thought of in a language that doesn't use a garbage collector it is
    mentioned in the Tween documentation and my class works as
    intended.
    The thing is although it works, it always bothers me when I
    don't know precisely
    why it works!
    If it's working due to the short life span of the class in
    question and thus simply missing the GC's window then this could be
    problematic. If at some point it is still alive when the GC is
    called then my class could be prematurely deleted.
    Maybe a class which has a reference to an "alive" MovieClip
    is immune from GC?
    I Hope someone can shed some light on this topic as the GC is
    something that is thinly documented to say the least!
    :theory
    p.s. first post!

    Hi,
    I would say it would be better use FREE itab at the end of the processing in your code. In the end-of-selection in your code, you can FREE all your itabs that were used in the program. This is one of the good approach of optimizing the memory.
    Regards
    Vimal

  • Can we explicitly stop the garbage Collector(which is running in background

    Hi all,
    we can clean up some memmory using System.gc() or freeMemory(). But my query is that we have to stop the gc which is running at the background in the JVM in java.
    I would request u all, to help me out in solving my query.
    Thanks & Regards,
    Mohan

    Calling System.gc() from the code is not good development practice. You shouldn't have to worry about the GC.
    Are you experiencing problems? Which ones?
    -Alexis

  • Using Java Program Can we know when the garbage Collector is called?

    Hi all,
    Can we create java program to find the time (Garbage collection time)
    I want to know the time limit of Garbage collection? How did the JVm knows the object is not reachable ?
    Pls help me
    regards,
    namanc

    Hi all,
    Can we create java program to find the time (Garbage
    collection time)Add "-verbose:gc" to your java command line.
    I want to know the time limit of Garbage collection?Can you be more specific?
    How did the JVm knows the object is not reachable ?See http://java.sun.com/docs/hotspot/gc1.4.2/.

  • Problem with the garbage collector

    Well, I have a problem, and it's quite a big deal.
    I don't understand why the java BC refuses to free the memory.
    I have made a VERY LITTLE example, so that everybody will see what the problem is made with.
    a frame with 2 buttons. the first one make another frame appears, which contains a quite big Swing component. The other is here in order to try to free the memory of this frame.
    Here are the 2 classes :
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class FirstClass extends JFrame{
    private JButton jButton1 = new JButton("free memory");
    private JButton jButton2 = new JButton("load frame");
    private MyFrameColor frame;
    public FirstClass() {
    jButton1.addMouseListener(new java.awt.event.MouseAdapter() {
    public void mouseClicked(MouseEvent e) {
    jButton1_mouseClicked(e);
    jButton2.addMouseListener(new java.awt.event.MouseAdapter() {
    public void mouseClicked(MouseEvent e) {
    jButton2_mouseClicked(e);
    this.getContentPane().add(jButton1, BorderLayout.NORTH);
    this.getContentPane().add(jButton2, BorderLayout.SOUTH);
    this.show();
    public static void main(String[] args)
    new FirstClass();
    import javax.swing.*;
    import java.awt.*;
    public class MyFrameColor extends JFrame {
    JColorChooser jColorChooser1 = new JColorChooser();
    public MyFrameColor() {
    this.getContentPane().add(jColorChooser1, BorderLayout.CENTER);
    }

    Some more info on garbage collection:
    http://www.javaworld.com/javaworld/jw-12-2001/jw-1207-java101.html?
    http://developer.java.sun.com/developer/technicalArticles/ALT/RefObj/

  • How the protected finalize method is called by garbage collector

    Dear All,
    I have a double regarding the calling mechanism of finalize method. The access specifier of finalize method is protected, not only that if a class overrides this method then also the finalize method can be protected in the subclass of Object. But the concept of protected access specifier is, from outside of the package it can be accessed only from subclass.
    The program (may be part of Garbage collector), which calls this (finalize) method mast not be in the same package (that is java.jang) nor it is a subclass of the class (whose finalize method it calls).
    Then how the finalize method is getting called by the garbage collector when it is protected?
    Regards,
    Gourab

    Refer to following link for the details
    http://www.me.umn.edu/~shivane/blogs/cafefeed/2005/09/why-is-finalize-method-protected.html
    The link gives answer to how a protected/private members are accessible to JVM or GC and why finalize is declared protected.

  • Help understand garbage collector behavour in case..

    Here is the case:
    class B{
    // members and methods
    class A{
    B memberAB;
    // other members and methods
    class C{
    B memberCB;
    public void takeAndKeep_B()
    A objA = new A();
    memberCB = objA.memberAB;
    //some code
    // other members and methods
    After takeAndKeep_B() finishes its job,
    garbage collector will not release
    memory occupied by objA
    (because there is still a reference to it's member memberAB, I think)
    Am I getting it right? Or the reason of memory leak is totaly unrelated to this case and I should look for it in some other place?
    I would appreciate any oppinions so mush.

    Here's how the garbage collector works: it collects any objects that the program cannot access. If an object cannot be accessed, it will be collected by the garbage collector if needed.
    In your code, after takeAndKeep_B() finishes, there are no references to the new A object that the objA reference points to. Thus, the A object can be collected by the garbage collector.
    Look at it this way: if the A class had a member named i that was an int, could your program access the i field of the A object you created after takeAndKeep_B() finishes? No, because the reference objA ceases to exist at the end of the method. Therefore, the object is unreachable and may be collected.
    There is no way for an unreferenced object not to be collected by the garbage collector. Java cannot leak memory in this way.

  • Understanding garbage collector output

    Hi all.
    My application uses an increasing amount of memory, and in order to solve the problem I have turned on the -verbosegc option. The output is as follows:
    <GC: managing allocation failure: need 1040 bytes, type=1, action=1>
    <GC: 504 milliseconds since last GC>
    <GC: freed 6530 objects, 288432 bytes in 10 ms, 35% free (661616/1887424)>
      <GC: init&scan: 1 ms, scan handles: 7 ms, sweep: 2 ms, compact: 0 ms>
      <GC: 4 register-marked objects, 7 stack-marked objects>
      <GC: 8 register-marked handles, 136 stack-marked handles>
      <GC: refs: soft 0 (age >= 32), weak 0, final 1, phantom 0>
    <GC: managing allocation failure: need 1040 bytes, type=1, action=2>
    <GC: 10 milliseconds since last GC>
    <GC: expanded object space by 1048576 to 2936000 bytes, 58% free>
    <GC: need to expand mark bits to cover 2560 bytes>Is any one able to explain this output for me? My problem is that the object space is expanded regularly and eventually the garbage collector writes "totally out of heap space" and an OutOfMemoryError occurs.
    My -version is
    java version "1.3.0"
    Java(TM) 2 Runtime Environment, Standard Edition
    Classic VM (build 1.3.0-1, native threads, jit)running on UNIX, Digital Alpha.
    Regards,
    Torben Lange

    Just a follow up on my memory leak problem which I have solved now.
    I had created a class which handles database connections. The constructor looked something like this:
    Connection connection;
    public DBConnection() {
      DriverManager.registerdriver(new myDriver());
      connection = DriverManager.getConnection(...);
    }My application creates an object of this class, uses it and then closes the object. This goes on all the time. (Yes, it could be handled another way by pooling database access or simply keep the connection open without closing it - but it isn't.)
    It seems that the registration of the driver in the constructor eventually will fill the memory - apparently the same driver is registered several times.
    Problem was solved when changing the code into the following:Connection connection;
    static boolean isRegistered = false;
    public DBConnection() {
      if (! isRegistered) {
        DriverManager.registerdriver(new myDriver());
        isRegistered = true;
      connection = DriverManager.getConnection(...);
    }Hope this could help others in the same situation.
    Regards,
    Torben Poort Lange

  • Garbage Collector blocks - weird behaviour

    Hi!
    After launching an application we ran into weird problems with the garbage collector. It's a combo of Jetty/JGroups/Helma-Application-Server and various other libraries on a RedHat 7.3 box. The problem occurs on a machine with relativly high load (~10 requests/sec) but doesn't come along with high load automatically.
    After some hours uptime the garbage collector blocks for increasingly longer intervals until the application is reachable only for seconds every few minutes. In concerns exclusivly minor GC in the new space. Each stop lasts for just 1/10000 seconds but that in a loop of 1000s times back-to-back.
    The logfile created by the -Xloggc option looks like this:
    20085.784: [GC 20085.785: [ParNew
    Desired survivor size 32768 bytes, new threshold 0 (max 0)
    : 71552K->0K(71616K), 0.0634410 secs] 380477K->312523K(511936K), 0.0639970 secs]
    Total time for which application threads were stopped: 0.0652310 seconds
    Application time: 8.7885840 seconds
    Total time for which application threads were stopped: 0.0005810 seconds
    Application time: 0.0005620 seconds
    Total time for which application threads were stopped: 0.0006080 seconds
    Application time: 0.0002630 seconds
    Total time for which application threads were stopped: 0.0004410 seconds
    Application time: 0.0001790 seconds
    Total time for which application threads were stopped: 0.0005480 seconds
    Application time: 0.0001670 seconds
    Total time for which application threads were stopped: 0.0003440 seconds
    Application time: 0.0001210 seconds
    Total time for which application threads were stopped: 0.0004450 seconds
    Application time: 0.0001590 seconds
    Total time for which application threads were stopped: 0.0004220 seconds
    Application time: 0.0002180 seconds
    20095.265: [GC 20095.265: [ParNew
    Desired survivor size 32768 bytes, new threshold 0 (max 0)
    : 71552K->0K(71616K), 0.0753260 secs] 384282K->317322K(511936K), 0.0759450 secs]
    Total time for which application threads were stopped: 0.0767720 seconds
    Application time: 0.3346050 seconds
    While the "Total time.." lines were printed, the app was unreachable. "Application time" usually marks the time the app was running between two garbage collections. It seems as if the garbage collector tries to stop the app, can't do it for whatever reason and tries again a moment later.
    We've tested any suitable garbage collector, we've tried out j2sdk1.4.2_02, j2sdk1.4.2_07, jdk1.5.0_01, jdk1.5.0_02, we've tried different machines to exclude hardware failure. It is hard to reproduce in a test environment but we've seen a few lines like above on a windows box too (no longer blocking times, tough). There aren't any OutOfMemoryErrors, the heap management looks fine. After GC about 3/4 of the heap are freed even while the above problem occurs, so we're ruling out a memory leak.
    Maybe someone here has stumbled across that problem or has any ideas what could trigger such a behaviour? After two weeks of debugging I've run out of ideas on where to look for a bug.
    Yours remotely,
    Stefan

    hi there
    Can u add -XX:+PrintHeapAtGC -XX:+PrintGC and show the portion of the log files?
    You are using the -XX:+ParNewGC? Any -XX:+UseConcMarkSweepGC?
    Also, add -XX:+DisableExplicitGC
    Hope this helps.

  • Garbage Collector seems not to run

    Hi!
    I have a problem with the garbage collector:
    To free memory, I regularly run the garbage collector in my app ( System.gc() ) after releasing resources by setting the reference variable to "null". But after some time I get an "out of heap memory" error. It seems that the gc doesn't run - I get the following result on the stdout:
    0 garbage collections (0 bytes collected)
    Is this possible? Or can I fix this problem?
    Thanks for your help

    Is it that the GC was not kicking-in even when you delete the references to the objects? That is true for any GC. GC will kick in only when you need more memory to create new objects
    Also, you need to tune your young generation space and increase it from default 2MB to 32MB which will avoid frequent young generation GCs. By setting Xmx to 1024 MB, VM will try to grow till 1024 MB and if it can't allocate because
    of less physical memory on your system, it will throw OutOfMemory errors.
    I suggest you try the following:
    1. Configure young generation to 32MB and old generation to 512 MB. This is how
    you start your app
    java -XX:MaxNewSize=32m -XX:NewSize=16m -Xms64m -Xmx512m -verbose:gc <app>
    This sets the initial heap size to 64MB. You can increase this if your initial startup memory requirement (static memory) is higher that 64MB.
    With Xmx set to 512MB, if some sessions die or are closed and heap size grows to 512MB, Full GC should kick in and you should be able to release memory for new sessions. Running with -verbose:gc will show if Full GC gets kicked in or not.
    2. Try can calculate the static memory required at any point of time and also how much garbage is collected in certain time period. Then using these values we can make changes in young and old generation sizes.

  • Garbage Collector Agent

    Hello, I want to know if the Garbage Collector deletes UnFoldered Document. I have created a custom relationship (ThumbnailRelationship) to attache a thumbnail file (a jpeg) to documents. Now, when some one delete a Document, do I have to create a Override to manually delete the ThumbnailRelationship and the Thumbnail document or the Garbage Collector will take care of it ? Where can I get more info on all those Agents running in the background ?
    Thank you
    null

    Hi -
    No, the GarbageCollectionAgent does not delete unfoldered objects. It cleans up references to objects that have been deleted. For example, say a user names testuser1 owns several documents. Then this user gets deleted - who owns the documents? Or more specifcally, what is the value stored in the owner column in the database table? The GarbageCollectionAgent firsts nulls these attributes, and for some attributes (PublicObject.Owner being one of them) it resets the existing objects to reference some other object.
    So, if you want the rightobject of a custom relationship to be automatically deleted when the leftobject is deleted, you'll have to do that via an override on your custom relationship subclass.
    I think the new admin guide has some more detailed information about the out-of-the-box agents.
    hope this helps-
    dave

Maybe you are looking for