Clear method and Garbage Collector

Hi Gurus,
Does the Clear method (hashtable, vector etc..) is a good option for garbage collection ?
In other words, if I have a vector V with 100 elements and I perform a V.clear(), am I sure that the 100 elements are now candidates for the Garbage Collection ?
Or is it better to write a loop performing a NULL assignment for each element of the vector ?

Hi schapel,
I know it's not a good idea to force the garbage collector, but let me explain what I am confronted with.
(FYI, I didn't write the source code. Comes from a 3rd party)
The aim is to build a jsp page which is the list of the files contained in a web server directory.
I have a "Directory" class, and a "File" class. To build the jsp, each directory of the webserver is represented by a directory class, and each file, ...by a file class.
To simplify, when the tree structure of the web server is build in memory, I create a jsp page to list the files, and then, I do not need the vector anymore. But the vector can be quite huge and each client will build his own vector at the begening of his session (and will never use it again during the session).
Don't you think it's usefull in that situation to free some memory ?

Similar Messages

  • I have a memory leak, objective-c 2.0, and garbage collector...

    the code i am using is a modification of the code/problem found in "Cocoa with Objective-C", chapter 3.
    i have tried to use the objective-c 2.0 garbage collector methodology, using @property, @synthesize, etc. when i run the code as listed below i get a leaking message.
    [Session started at 2008-02-01 23:33:37 -0500.]
    2008-02-01 23:33:38.070 SongsFoundationTool[28876:10b] * _NSAutoreleaseNoPool(): Object 0x2040 of class NSCFString autoreleased with no pool in place - just leaking
    Stack: (0x96b10178 0x96a3e0f8)
    2008-02-01 23:33:38.075 SongsFoundationTool[28876:10b] Song 1: We Have Exposive
    2008-02-01 23:33:38.076 SongsFoundationTool[28876:10b] * _NSAutoreleaseNoPool(): Object 0x2060 of class NSCFString autoreleased with no pool in place - just leaking
    Stack: (0x96b10178 0x96a3e0f8)
    2008-02-01 23:33:38.078 SongsFoundationTool[28876:10b] Song 2: Loops of Fury
    The Debugger has exited with status 0.
    when i include the commented out section, in the implementation file section, the description method, and use song1 and song2, in main, instead of song1.name and song2.name the program seems to run fine.
    The Debugger has exited with status 0.
    [Session started at 2008-02-01 23:38:24 -0500.]
    2008-02-01 23:38:24.375 SongsFoundationTool[28936:10b] Song 1: We Have Exposive
    2008-02-01 23:38:24.379 SongsFoundationTool[28936:10b] Song 2: Loops of Fury
    The Debugger has exited with status 0.
    please help me understand what's happening here.
    also, why was it necessary to use
    @property(copy, readwrite) NSString *name;
    @property(copy, readwrite) NSString *artist;
    instead of
    @property(readwrite) NSString *name;
    @property(readwrite) NSString *artist;
    thanks everyone, the code is below.
    // ....................... header file ...............
    #import <Cocoa/Cocoa.h>
    @interface Song : NSObject {
    NSString *name;
    NSString *artist;
    @property(copy, readwrite) NSString *name;
    @property(copy, readwrite) NSString *artist;
    @end
    //.................... the implementation file ..................
    #import "Song.h"
    @implementation Song
    @synthesize name;
    @synthesize artist;
    -(NSString *) description
    return [ self name ];
    @end
    //................................ main............................
    #import <Foundation/Foundation.h>
    #import "Song.h"
    int main (int argc, const char * argv[]) {
    Song *song1 = [ [ Song alloc ] init ];
    song1.name= @"We Have Exposive" ;
    [ song1 setArtist: @"The Future Sound Of Londown" ];
    Song *song2 = [ [ Song alloc ] init ];
    [ song2 setName: @"Loops of Fury" ];
    [ song2 setArtist: @"The Chemical Brothers" ];
    // Display Object
    NSLog( @"Song 1: %@", song1.name );
    NSLog( @"Song 2: %@", song2.name );
    // include statements below if -description method is uncommented
    // then comment out the two statements above. no memory leak if the code
    // is used from the statements below and - description is not commented out and
    // the two NSLog statements above are commented out.
    NSLog( @"Song 1: %@", song1 );
    NSLog( @"Song 2: %@", song2 );
    return 0;
    }

    Normally, your main only has a call to NSApplicationMain(). If you aren't doing a traditional MacOS X application, you will still want at least NSApplicationLoad() to get enough of the runtime to avoid those messages.
    I don't know for sure about the syntax of Objective-C 2.0. That stuff is all new. What error message are you getting that indicated that (copy, readwrite) is required? Could you provide a link to the actual example source? I did a quick check and assign and readwrite are the defaults. It is possible that readwrite by itself makes no sense. But I'm just guessing.

  • CORBA and garbage collector

    Hi,
    I�m writing a server with a method create(), which returns a new object supplying a home banking service for the clients.
    My question is : when a given client has finished with the home banking object, do I need to call the gc, or is there an efficient one with CORBA (a kind of distributed garbage collector) ?
    Thank you in advance

    Maybe you heard about Distributed Garbage Collector (DGC)? Don't rely on this, since IIOP does not support this. Use PortableRemoteObject.unexportObject() to make remote objects that are no longer in use available for garbage collection.
    Bert

  • EMCC and Garbage Collector

    We have 2 CUCM clusters connected via an ICT. We are migrating users from CM8.6 to CM10.5. During the migration we are changing Users AD attributes so that they disappear from CM8. As this marks the user as Inactive in CM8 (and deletes after 24hrs) this prevents the User from logging into CM10 with EMCC.
    Is there a way around this?
    ie force the garbage collector to run immediately and delete the user
    or remove certain fields in CUCM 8 against the user so that they can login using CUCM10 credentials?
    Thanks
    Rich

    I think you can do something clever here. You can convert the inactive user on cucm 8 back to a standard cucm user and then delete them. This way you can control when to remove the user instea dof waiting for garbage collection. You become your own garbage man :)
    You can conver the users back to standard CUCM users using sql query update...Ths is easy to do
     run sql update enduser set status=1 ( this is the general command to make all users standard cucm users..you don't want to run this..)
    Use this command to make specific users active. You need to use the users extension to filter which user gets converted to standard cucm user
    run sql update enduser set status=1 where telephonenumber like ‘2%’
     This command will update users with extension beginning with 2
    or
    run sql update enduser set status=1 where telephonenumber = '2001'
    This will convert user with extension 2001 to a standard cucm user
     To make sure you got all the users you can use the command
    run sql select * from enduser where status=0
     This should return zero entry. If you find any user there then use the update command on those users

  • RemoveChild and Garbage Collector

    I am still fuzzy on the Actionscript 3 framework.
    If I remove a child from a container, is the removed child
    automatically eligible for the garbage collection?
    If not – what should I do to make it eligible?
    If yes – what can be done to prevent it from being
    permanently deleted should I need it?
    container.removeChild(myDisplayObject)
    Thank you!

    kglad,
    Thank you very much for you response - things are much
    clearer now.
    I am trying to figure out some standard ways to deal with
    unneeded objects. I am relatively new in OOP (and my OOP education
    comes from JS and Flash) and it is not very obvious to me yet how
    to approach garbage collection in general (and I realize how
    important this kind routine is).
    If this is not very time consuming - could you please share
    some bullet points of how you do that. Do you have, say, a class
    that performs clean up routine for all the objects or, may be, each
    class has to have some method that cleans up after it? Also, what
    would be an optimal way to keep track of the objects (some central
    depository/library) so that one can find them easily. I've noticed
    that there is a new class Dictionary in AS3 - can it be useful for
    this task?
    I know that I want too much and I need to pick up a book or
    two on OOP but, still, I like to hear developers' experiences not
    only because I tend to take short cuts but also because in many
    cases what experience dictates is much more useful than academical
    elaborations.
    Again, thank you very much,
    Andrei

  • Primitives and garbage collector

    Hi everyone,
    Do primitives get garbage collected?
    Is it recommended to set all references to null in a classes finalize method?
    Thanks

    Do primitives get garbage collected?No.
    Is it recommended to set all references to null in
    in a classes finalize method?No, there is no point in doing that.

  • Regarding remove() and clear () method

    when we call clear() and remove(index) method for vector or hashtable, the element will be removed and the size decreases by one . The question is wheteher the memory will get freed when these methods are called?

    Hi,
    Vectors hold only references to other objects. Hence, when you "add or remove" elements to vectors, you are only adding or removing references to other objects in the heap.
    Memory taken by objects in the heap is freed as per the whims of the garbage collector. Unless your program does some memory-intensive computation, the garbage collector might not even run during your program's execution phase.
    If you have declared Vector v = new Vector();, the JRE will create a vector object in the heap, capable of storing 10 references. If you try to add an 11th reference to the vector, the Vector object will grow automatically by a default increment. Since in your code you are adding and removing references continuously, the Vector size will remain the same as long as the number of references never exceeds 10.
    Regards,
    Kumar.

  • 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.

  • 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

  • Garbage Collector and verbose GC

    Hi, we are getting strange behavior with the garbage collector if the verbosegc is enabled. The gc still report it is collecting memory but none is ever freed. If the option is not enabled the problem disapear. Has anyone experience something similar?
    We are running on Sun 5.8 with weblogic 5.1 sp 8 and jdk 1.2.2_09

    Can you post some of the verbosegc output? Output with -XX:+PrintGCDetails might
    help a little more.

  • Garbage collector and JPEG decoder

    Hi,
    I have a problem with the garbage collector decoding JPEG images received on a TCP socket. The process works but each time that I have to decode an image I have to create a new decoder, this causes that the garbage collector starts to work constantly looking for memory. When the gc starts to work the streamed images almost stop since the gc takes all the process.
    Here is the code that has the problem. On this code you can see that I create a new ByteArrayInputStream and a MediaTracker, but I know how reuse this objets, the problem is on the decoder.
    Does any one have an idea of how to solve it?
    Thanks
    public void cargarImagen(Visualizador vision,
                                  Cabecera cabImg,
                                  boolean completa,
                                  boolean grabar,
                                  boolean pantCIF,
                                  JFrame1 jf1)throws Exception{
            Visualizador aux;
            ByteArrayInputStream byis = new ByteArrayInputStream(s1.buffer);
            try{
                    decoder=JPEGCodec.createJPEGDecoder(byis);
                    try{
                           // decode
                                                   vision.image_Webcam=decoder.decodeAsBufferedImage();
                    }catch(ImageFormatException b){
                      System.out.println("Incorrect image format");
                    }catch(Exception a){
                      System.out.println("Incorrect image");
                    mediaTracker_track = new MediaTracker(vision);
                    mediaTracker_track.addImage(vision.image_Webcam, 0);
                 mediaTracker_track.waitForID(0,500);
            }finally{
                      byis.close();
            if(mediaTracker_track.statusID(0, false) == MediaTracker.COMPLETE){
                  vision.repaint();
             else{    /* incorrect image */
                  vision.image_Webcam = null;
                  System.out.println("Discarded image");
    }

    I think that this is not the case. Images come from a TCP connection and the application start to read the next image from the socket when the previous one has been decoded and painted.
    So, images are not stored on memory and the received images rate depens on how fast is the application reading images from the socket.
    However, it is a good idea to start gc before getting next image, the average rate will decrease but it will avoid the "jumps" on visualization.

  • Garbage collector and JVM

    is garbage collector is part of JVM or it is part of our program process.
    ie ... if we are having 3 programs running at the same time will we have one garbage collector for them or we will have 1 each ofor each process.
    what is the priority of the garbage collector as a process.

    GC is a part of JVM. GCs from different JVMs never
    intersect.hmm.
    So if i am having 3 programs of java running on one machine. how much JVM will i be running ... i guess one. so will they share one GC ???
    what is the priority of GC at process level???

  • Garbage collector request

    I think so many programmers are concerned with optimization and in particular the garbage collector that Sun should provide some serious advice and tips on improving the chances that Objects they don't want can be properly garbage collected. For example, setting pointers to null after they are used.

    Unfortunately (IMHE) the word optimization seems to be a synonym nowadays for "I wasn't able to code this the way I wanted to so now I need to make it faster".
    Most real-world applications, in todays world of cheap cycles and cheap bandwidth, rarely need optimizing, they DO need to be built robustly and securely with the focus on data integrity and consistency. Anyone who needs such amazing speed-up should really be looking at C rather than Java. Java was never designed to be the fastest language ever but it was designed to tackle the nasty issues related to network programming and online deployment of services and applications.
    The question of "Objects that aren't wanted are GC'd" is not relevant since if you really don't want the object anymore then why should it concern you whether it is cleared up. If you have designed your application properly then your code should reflect your "don't want it status" for that object, if it then gets GC'd, great, if not, then it should do at some point. As "schapel" indicates coding so that you actually do not require the object anymore is the way to go...although the methods close and dispose are usually designed to ensure that OS resources are cleaned up and made available for reuse as anyone who opens up too many files and doesn't close them on Unix will you...

  • Clearing Images and Destroying Instances

    Two separate questions here.
    First I'd like to know how to clear an image that has been drawn, with it being on a random background with multiple colors, without having to redraw the background over and over again. I have an image that moves across the screen and I have the background update only when it needs to to save processing power, but now, obviously, the moving image remains drawn wherever it goes. That or if there's a way to "move" an already drawn image.
    Secondly, I'd like to know how to delete an instance of a class from within that class. I have a class that gets called a lot (example: Caller.java), and each time it's called, it creates a new instance of another class (example: NewClass.java), but when Caller.java is called, it is only used once, and I don't want all those instances to just remain there. I'd like to force GC to take care of them at the end of their tasks.
    If anyone can provide answers to either of those questions, thank you.

    hi,
    try to read this it may helpfor the subject:its from thinking in java 2nd edition by bruce eckel:
    Cleanup: finalization and
    garbage collection
    Programmers know about the importance of initialization, but often forget the importance of cleanup. After all, who needs to clean up an int? But with libraries, simply �letting go� of an object once you�re done with it is not always safe. Of course, Java has the garbage collector to reclaim the memory of objects that are no longer used. Now consider a very unusual case. Suppose your object allocates �special� memory without using new. The garbage collector knows only how to release memory allocated with new, so it won�t know how to release the object�s �special� memory. To handle this case, Java provides a method called finalize( ) that you can define for your class. Here�s how it�s supposed to work. When the garbage collector is ready to release the storage used for your object, it will first call finalize( ), and only on the next garbage-collection pass will it reclaim the object�s memory. So if you choose to use finalize( ), it gives you the ability to perform some important cleanup at the time of garbage collection. [ Add Comment ]
    This is a potential programming pitfall because some programmers, especially C++ programmers, might initially mistake finalize( ) for the destructor in C++, which is a function that is always called when an object is destroyed. But it is important to distinguish between C++ and Java here, because in C++ objects always get destroyed (in a bug-free program), whereas in Java objects do not always get garbage-collected. Or, put another way: [ Add Comment ]
    Garbage collection is not destruction.
    If you remember this, you will stay out of trouble. What it means is that if there is some activity that must be performed before you no longer need an object, you must perform that activity yourself. Java has no destructor or similar concept, so you must create an ordinary method to perform this cleanup. For example, suppose in the process of creating your object it draws itself on the screen. If you don�t explicitly erase its image from the screen, it might never get cleaned up. If you put some kind of erasing functionality inside finalize( ), then if an object is garbage-collected, the image will first be removed from the screen, but if it isn�t, the image will remain. So a second point to remember is: [ Add Comment ]
    Your objects might not get garbage-collected.
    You might find that the storage for an object never gets released because your program never nears the point of running out of storage. If your program completes and the garbage collector never gets around to releasing the storage for any of your objects, that storage will be returned to the operating system en masse as the program exits. This is a good thing, because garbage collection has some overhead, and if you never do it you never incur that expense. [ Add Comment ]
    What is finalize( ) for?
    You might believe at this point that you should not use finalize( ) as a general-purpose cleanup method. What good is it? [ Add Comment ]
    A third point to remember is:
    Garbage collection is only about memory.
    That is, the sole reason for the existence of the garbage collector is to recover memory that your program is no longer using. So any activity that is associated with garbage collection, most notably your finalize( ) method, must also be only about memory and its deallocation. [ Add Comment ]
    Does this mean that if your object contains other objects finalize( ) should explicitly release those objects? Well, no�the garbage collector takes care of the release of all object memory regardless of how the object is created. It turns out that the need for finalize( ) is limited to special cases, in which your object can allocate some storage in some way other than creating an object. But, you might observe, everything in Java is an object so how can this be? [ Add Comment ]
    It would seem that finalize( ) is in place because of the possibility that you�ll do something C-like by allocating memory using a mechanism other than the normal one in Java. This can happen primarily through native methods, which are a way to call non-Java code from Java. (Native methods are discussed in Appendix B.) C and C++ are the only languages currently supported by native methods, but since they can call subprograms in other languages, you can effectively call anything. Inside the non-Java code, C�s malloc( ) family of functions might be called to allocate storage, and unless you call free( ) that storage will not be released, causing a memory leak. Of course, free( ) is a C and C++ function, so you�d need to call it in a native method inside your finalize( ). [ Add Comment ]
    After reading this, you probably get the idea that you won�t use finalize( ) much. You�re correct; it is not the appropriate place for normal cleanup to occur. So where should normal cleanup be performed? [ Add Comment ]
    You must perform cleanup
    To clean up an object, the user of that object must call a cleanup method at the point the cleanup is desired. This sounds pretty straightforward, but it collides a bit with the C++ concept of the destructor. In C++, all objects are destroyed. Or rather, all objects should be destroyed. If the C++ object is created as a local (i.e., on the stack�not possible in Java), then the destruction happens at the closing curly brace of the scope in which the object was created. If the object was created using new (like in Java) the destructor is called when the programmer calls the C++ operator delete (which doesn�t exist in Java). If the C++ programmer forgets to call delete, the destructor is never called and you have a memory leak, plus the other parts of the object never get cleaned up. This kind of bug can be very difficult to track down. [ Add Comment ]
    In contrast, Java doesn�t allow you to create local objects�you must always use new. But in Java, there�s no �delete� to call to release the object since the garbage collector releases the storage for you. So from a simplistic standpoint you could say that because of garbage collection, Java has no destructor. You�ll see as this book progresses, however, that the presence of a garbage collector does not remove the need for or utility of destructors. (And you should never call finalize( ) directly, so that�s not an appropriate avenue for a solution.) If you want some kind of cleanup performed other than storage release you must still explicitly call an appropriate method in Java, which is the equivalent of a C++ destructor without the convenience. [ Add Comment ]
    One of the things finalize( ) can be useful for is observing the process of garbage collection. The following example shows you what�s going on and summarizes the previous descriptions of garbage collection:
    //: c04:Garbage.java
    // Demonstration of the garbage
    // collector and finalization
    class Chair {
    static boolean gcrun = false;
    static boolean f = false;
    static int created = 0;
    static int finalized = 0;
    int i;
    Chair() {
    i = ++created;
    if(created == 47)
    System.out.println("Created 47");
    public void finalize() {
    if(!gcrun) {
    // The first time finalize() is called:
    gcrun = true;
    System.out.println(
    "Beginning to finalize after " +
    created + " Chairs have been created");
    if(i == 47) {
    System.out.println(
    "Finalizing Chair #47, " +
    "Setting flag to stop Chair creation");
    f = true;
    finalized++;
    if(finalized >= created)
    System.out.println(
    "All " + finalized + " finalized");
    public class Garbage {
    public static void main(String[] args) {
    // As long as the flag hasn't been set,
    // make Chairs and Strings:
    while(!Chair.f) {
    new Chair();
    new String("To take up space");
    System.out.println(
    "After all Chairs have been created:\n" +
    "total created = " + Chair.created +
    ", total finalized = " + Chair.finalized);
    // Optional arguments force garbage
    // collection & finalization:
    if(args.length > 0) {
    if(args[0].equals("gc") ||
    args[0].equals("all")) {
    System.out.println("gc():");
    System.gc();
    if(args[0].equals("finalize") ||
    args[0].equals("all")) {
    System.out.println("runFinalization():");
    System.runFinalization();
    System.out.println("bye!");
    } ///:~
    The above program creates many Chair objects, and at some point after the garbage collector begins running, the program stops creating Chairs. Since the garbage collector can run at any time, you don�t know exactly when it will start up, so there�s a flag called gcrun to indicate whether the garbage collector has started running yet. A second flag f is a way for Chair to tell the main( ) loop that it should stop making objects. Both of these flags are set within finalize( ), which is called during garbage collection. [ Add Comment ]
    Two other static variables, created and finalized, keep track of the number of Chairs created versus the number that get finalized by the garbage collector. Finally, each Chair has its own (non-static) int i so it can keep track of what number it is. When Chair number 47 is finalized, the flag is set to true to bring the process of Chair creation to a stop. [ Add Comment ]
    All this happens in main( ), in the loop
    while(!Chair.f) {
    new Chair();
    new String("To take up space");
    You might wonder how this loop could ever finish, since there�s nothing inside the loop that changes the value of Chair.f. However, the finalize( ) process will, eventually, when it finalizes number 47. [ Add Comment ]
    The creation of a String object during each iteration is simply extra storage being allocated to encourage the garbage collector to kick in, which it will do when it starts to get nervous about the amount of memory available. [ Add Comment ]
    When you run the program, you provide a command-line argument of �gc,� �finalize,� or �all.� The �gc� argument will call the System.gc( ) method (to force execution of the garbage collector). Using the �finalize� argument calls System.runFinalization( ) which�in theory�will cause any unfinalized objects to be finalized. And �all� causes both methods to be called. [ Add Comment ]
    The behavior of this program and the version in the first edition of this book shows that the whole issue of garbage collection and finalization has been evolving, with much of the evolution happening behind closed doors. In fact, by the time you read this, the behavior of the program may have changed once again. [ Add Comment ]
    If System.gc( ) is called, then finalization happens to all the objects. This was not necessarily the case with previous implementations of the JDK, although the documentation claimed otherwise. In addition, you�ll see that it doesn�t seem to make any difference whether System.runFinalization( ) is called. [ Add Comment ]
    However, you will see that only if System.gc( ) is called after all the objects are created and discarded will all the finalizers be called. If you do not call System.gc( ), then only some of the objects will be finalized. In Java 1.1, a method System.runFinalizersOnExit( ) was introduced that caused programs to run all the finalizers as they exited, but the design turned out to be buggy and the method was deprecated. This is yet another clue that the Java designers were thrashing about trying to solve the garbage collection and finalization problem. We can only hope that things have been worked out in Java 2. [ Add Comment ]
    The preceding program shows that the promise that finalizers will always be run holds true, but only if you explicitly force it to happen yourself. If you don�t cause System.gc( ) to be called, you�ll get an output like this:
    Created 47
    Beginning to finalize after 3486 Chairs have been created
    Finalizing Chair #47, Setting flag to stop Chair creation
    After all Chairs have been created:
    total created = 3881, total finalized = 2684
    bye!
    Thus, not all finalizers get called by the time the program completes. If System.gc( ) is called, it will finalize and destroy all the objects that are no longer in use up to that point. [ Add Comment ]
    Remember that neither garbage collection nor finalization is guaranteed. If the Java Virtual Machine (JVM) isn�t close to running out of memory, then it will (wisely) not waste time recovering memory through garbage collection. [ Add Comment ]
    The death condition
    In general, you can�t rely on finalize( ) being called, and you must create separate �cleanup� functions and call them explicitly. So it appears that finalize( ) is only useful for obscure memory cleanup that most programmers will never use. However, there is a very interesting use of finalize( ) which does not rely on it being called every time. This is the verification of the death condition[29] of an object. [ Add Comment ]
    At the point that you�re no longer interested in an object�when it�s ready to be cleaned up�that object should be in a state whereby its memory can be safely released. For example, if the object represents an open file, that file should be closed by the programmer before the object is garbage-collected. If any portions of the object are not properly cleaned up, then you have a bug in your program that could be very difficult to find. The value of finalize( ) is that it can be used to discover this condition, even if it isn�t always called. If one of the finalizations happens to reveal the bug, then you discover the problem, which is all you really care about. [ Add Comment ]
    Here�s a simple example of how you might use it:
    //: c04:DeathCondition.java
    // Using finalize() to detect an object that
    // hasn't been properly cleaned up.
    class Book {
    boolean checkedOut = false;
    Book(boolean checkOut) {
    checkedOut = checkOut;
    void checkIn() {
    checkedOut = false;
    public void finalize() {
    if(checkedOut)
    System.out.println("Error: checked out");
    public class DeathCondition {
    public static void main(String[] args) {
    Book novel = new Book(true);
    // Proper cleanup:
    novel.checkIn();
    // Drop the reference, forget to clean up:
    new Book(true);
    // Force garbage collection & finalization:
    System.gc();
    } ///:~
    The death condition is that all Book objects are supposed to be checked in before they are garbage-collected, but in main( ) a programmer error doesn�t check in one of the books. Without finalize( ) to verify the death condition, this could be a difficult bug to find. [ Add Comment ]
    Note that System.gc( ) is used to force finalization (and you should do this during program development to speed debugging). But even if it isn�t, it�s highly probable that the errant Book will eventually be discovered through repeated executions of the program (assuming the program allocates enough storage to cause the garbage collector to execute). [ Add Comment ]

  • JNI - Garbage Collector Problem ?

    Hi,
    I've got a JNI methode, which ceate and lauch a Process in c++ (a process to make VoIP).
    - this methode is returning an int=the pointer to the instance (which implement this process) so that othet JNI methode can have access to the main instance.
    Under windows, everything works fine, but
    Using linux:
    I add a memory wathcher on my program to see the memory used by the application / memory available for the JVM.
    The memory used by the application is growing (this is normal at this point), but when the GC is callled (by the system) the Java application is frozen (no error message), and I have to kill it. On the oter side, the Dll is running normally !
    My theory is that under Linux, the GC is "feeing" the memory used by the c++ process , then java is trying to write on it, but have no access, or somehing like that.
    Is there any option to be check this theory: as Java is retunring no error, but just freezing, it is not very clear to understand.
    I tried, using JNI, but removing the Process in it, just calling a basic operation, and there is no bug.
    Is there a special procedure to do on LINUX, for managing the Garbage Collector with JNI ?
    Here is a piece of code :
    /***********Java Side******************/
    //The JNI def:
    public class JNIWrapper {
         public JNIWrapper() {
         // create the h323 Process
    public native int create();
    ///The class managing the JNI methodes and containing the pointer to the dll main class
    public class CallControlH323 implements CallControl {
         int h323StackPtr; //Pointer to the h323stack, needed in the c++ side
         JNIWrapper myJNIWrapper;
         String options; //option for the CallControl configuration
         public CallControlH323(){
              myJNIWrapper = new JNIWrapper();
         public void configure(String options, String codecs) {
              h323StackPtr = myJNIWrapper.create();
    /*************************C++ side*****************/
    //JNI functions (file JNITerminal.cxx)
    #include "JNITerminal.h"
    #include <stdio.h>
    // Java Global Variables
    jobject jobj;
    JavaVM *jvm;
    /** Create the MainInterface **/
    JNIEXPORT jint JNICALL Java_ca_sess_voicesess_terminal_JNIWrapper_create
         (JNIEnv *env, jobject obj)
         // Make object a Global Reference
         jobj = env->NewGlobalRef(obj);
         // Get Java VM
         env->GetJavaVM(&jvm);
         //create and start the main Process
         MainInterface * mainInterface;
         mainInterface = new MainInterface();
         return ( ( jint ) mainInterface );
    MainInterface inherite from PProcess (from Pwlib), it is the top process of the dll application
    MainInterface::MainInterface():PProcess("", "", MAJOR_VERSION, MINOR_VERSION, BUILD_TYPE, BUILD_NUMBER)
    #ifdef MSCVER
    #pragma warning(disable:4355)
    #endif
    #ifdef MSCVER
    #pragma warning(default:4355)
    #endif
         ShowOutputs("H323Lib: Create Main Interface");
    void MainInterface::Main () {}
    MainInterface::~MainInterface()
    /////////////////////////////////////////////////////////////////////////7
    If you have any suggestion, comment, help, don hesitate !!
    Thanks for your help
    Bart

    I also added the option -verbosegc to the java command.
    I noticed that the bug arrived after a Full gc:
    [Full GC 23301K->12351K(24844K), 0.3737040 secs]

Maybe you are looking for