"finally" how effective is it for garbage collector ?

I am a Java Developer and a SCJP2 with 99% score. Recently, I was in a debate with one of my colleague over the use of }try { //code } finally{}" for helping in the garbage collection of method level objects. For e.g. consider the following code.
////// code starts //////////
public class TestFinallyGC {
public void aMethod() {
java.util.ArrayList myList = null ;
try {
myList = new java.util.ArrayList();
// do something with the list
} finally {
myList = null;
////// code ends //////////
Now, my question is : How effective is or useful is the above finally block in above code for the garbage collection of the ArrayList object ? Because if the "finally" block is always going to be at the end of the method then by the time the method finishes (and the finally block also executes at around same time) the variable "myList" will also go out-of-scope and the object it was representing becomes eligible for garbage collection, no matter whether we explicitly set it to "null" or not.
Is the above conslusion correct ?
--Vinod.

How did you decide that references on the stackwere
not reachable?Personally I decided it because after I exit a block
or return from a function, the variables defined there
go irreversibly out of scope, so there is no way for
me to ever interact with them again. And since those
where the only references to the large arrays, they
were unreachable and eligible for garbage collection.
Ok. But something owns the stack. At the something is not going out of scope. It still owns the stack.
Given that reachable does not just
mean user threads but JVM threads as well.I did not create any threads, so there is just the
"Main" thread.
As far as I know there are no JVM threads. That is to
say, I read the JLS and did not find their existence
defined there. It does say that finalizers may be run
on "any thread" but does not say that there must be a
separate finalizer thread. Yes as far as you know. However, none of the specs disallow the JVM from creating JVM threads. The spec is specific that it unreachable from a thread, but it does not specify how those threads come into existence.
Basically since the jls
does not say there are JVM threads, we must assume
that if they exist then the behavior would be the same
as if they did not.
No. That is not the way one should approach a spec. Anything that the spec does not specify must be considered to be undefined. It can have any possible behavior.
So the stack might belong to a java object/thread or it might not. Either is possible. If it doesn't then it is unreachable and thus collectible. If it does then it is not.
So both suppositions are equally valid. So presumably the answer to my question would have been that you are assuming that it does not belong to a java object.
(Naturally we are both aware that the stack is always reachable by the system. It is not a temporary. Thus the question is only if it belongs to a java object or not. Or possibly if it does belong to a java object then whether references on it are cleared after a method exit.)
And as far
as I know there is no reason to think that thestack
might not be in the java domain space (althoughthat
might suggest a chicken and egg problem.)??
What are you talking about? What is the "java domain
space"? I don't know what that means.
JVMs always consist of C/C++ code with some mixture of Java. There is always C/C++ and there is always java. The first is true because the OS will not run java byte codes. The second is true because the JVM must always load java.lang.String.
Given this, it means that in any JVM there will be a domain space that consists of java entities and a domain space that consists of something else (C/C++.)
The question here is whether the stack is part of the C/C++ space or part of the java space.
The only stack I know about is the one that starts at
Thread.run() and goes up through all the methods that
have been called, ending at the method currently
executing. There is nothing above or below the stack.
When you call a method, its size increases by one,
and when a method returns, the size decreases by
one.
Doubt it. The stack pointer might move but I doubt the stack size increases and decreases. There are performance reasons for not doing that along with system management problems.
Of course if you have a reference that states otherwise then I would be glad to read it.
I think the whole point of this discussion is "what
happens to the stack frames that are lost when methods
return". My answer: They cease to exist, any
references they may have contained are lost and if
they were the only references to a given object it
would be immediately available for garbage
collection.

Similar Messages

  • How effective is Bootcamp for games? MW3?Any help much appreciated

    Hi all,
    I am going to purchase an iMac over Christmas but there's just one final niggle I need to get out of my brain.. Just how effective is Bootcamp for running windows games on an iMac? Will it work cohesively with the latest games such as MW3? Are there any major downfalls?
    Thanks for the any help in advance
    -Aaron

    there is an entire forum dedicated to bootcamp: https://discussions.apple.com/community/windows_software/boot_camp.  Asking the question there is probably your best bet .

  • * How about flash play 8 Garbage Collector working?

    Hi, I need to add some Image controls dynamically, yes,the
    number of those are unpredictable.
    My code to create them like this:
    quote:
    public function addImg(name:String, x:Number, y:Number):void
    var sm1:Image = new Image();
    sm1.source = "imgs/down_medium.gif";
    sm1.name = name;
    sm1.x = x;
    sm1.y = y;
    this.addChild(sm1);
    Then, it appeared in my application. if I add numbers of
    Image in my stage, they eat my memory crazily.
    so I want to kill some Image which is not in use, but I
    crashed.
    An Image named "img4kill" in stage, it's index in
    this.getChildren() is4, and it holds a image which size is about
    230K.
    I tried to kill it like this:
    quote:
    this.removeChildAt(4);
    yes, it's remove from the stage in faith, but I watched the
    memory that the browser using, before and after killing it.
    I found the memory it takes is not released.
    How can I kill it from both the stage and memory ? I tried
    the global function "delete" ,but failed too.
    I know that flash play 8.5 and later use a powerfull
    GC(garbage collector), but in the sample above, it dose't work for
    me.
    who can save me from this mud layer?any ideas?
    thanks a lot .
    (sorry about my ugly english)
    [email protected]

    Don't worry, the garbage collector will work very well in this case (and in every other case too :) ). It will only collect an object when no more references are pointing to it. Your array still holds a reference to all the items it contains (unless you explicitly do array[index] = null).
    There are only three ways that I know of to destroy a reference to an Object: 1). Set the reference to null 2). Let the reference fall out of scope 3) reassign the reference to another object
    The garbage collector will also be able to collect objects that have a cyclical references as long as none of the objects in the cycle are reachable.
    It pays to understand the ins and outs of garbage collection and memory management in the VM. Knowing that will let you know, for example, that allocating an Object in Java is a very cheap operation (while it is pretty expensive in C/C++).
    Check http://www.ibm.com/developerworks/java/library/j-jtp10283/ and http://www.ibm.com/developerworks/java/library/j-jtp11253/ and for more details about the GC
    Also don't worry about the performance impact of setters and getters, either the javac compiler or the Virtual Machines Just In Time Compiler will inline those small methods.
    In short don't worry about such low level performance problems and concentrate on your coding style and algorithms. The Hotspot JVM is an amazingly efficient piece of software. It also include a lot of optimizations that work very well in optimizing "standard" code. The more normally you code, the faster your program will be, so don't try clever optimizations tricks, they probably won't work well in java.
    Read the following articles for some discussion about performance in Java:
    http://www.ibm.com/developerworks/java/library/j-jtp04223.html
    http://www.ibm.com/developerworks/java/library/j-jtp09275.html
    http://www.ibm.com/developerworks/java/library/j-jtp01274.html

  • ThreadDumpScan tool for garbage collector trace analysis

    Hello,
    I would like to use the non official SAP tool ThreadDumpScan in order to have these nice graphs concerning the garbage collection.
    I have downloaded the std_server0.out from my server, where I can find  my GC activity, for instance :
    <GC(1): Bytes Traced =0 (Foreground: 0+ Background: 0) State = 3 >
    >> 2 modes = 2,0 (0) free After GC (reg,wild):1414879256,644244672
      <GC(1): GC cycle started Wed Apr 18 01:53:12 2007
      <GC(1): heap layout:  (1464142288/1503237440) (644244672/644244672)  /0>
      <GC(1): freed 49263032 bytes, 98% free (2108386960/2147482112), in 194 ms>
      <GC(1): mark: 171 ms, sweep: 23 ms, compact: 0 ms>
      <GC(1): In mark: root scan 150 ms>
      <GC(1): refs: soft 260 (age >= 0), weak 0, final 385, phantom 0>
    <AF[1]: completed in 214 ms>
    But the thing is that when I run the command "DumpScan.bat std_server0.out", I get the following error :
    no -verbose:gc output found
    On a former project, it was working properly, so I do not know why I get this error. The std_server0.out seems fine. I have gone through all the documentation provided with the tool but nothing in there, and the available documentation on this tool is very poor on sdn. Does anyone know what could be the problem ?
    Thanks for your help,
    Best regards,
    Guislain

    Guislain Libessart,
    Did you ever get this tool working? I am having the same issue.

  • Garbage Collector - which one?

    How can I tell which Garbage collector is being invoked?
    I'd like proof that serial or parallel is indeed running.

    Which version of the platform are you running?
    If you run with the -XX:+PrintGCDetails flag, when a collection happens it will print a line like [GC [PSYoungGen: 184K->128K(10752K)] 184K->128K(35328K), 0.0145377 secs] where the "PSYoungGen" indicates that you are using the parallel young generation scavenger. If it instead says [GC [DefNew: 1791K->192K(1984K), 0.0146794 secs] 1791K->1706K(6080K), 0.0148851 secs] then "DefNew" says you are using the default serial young generation collector. Other variations are possible depending on which collector you are running. But those are the two you asked about.
    This, and much more, is described in http://java.sun.com/docs/hotspot/gc5.0/gc_tuning_5.html or http://java.sun.com/javase/technologies/hotspot/gc/gc_tuning_6.html depending on what version of the JDK you are running. There's also http://java.sun.com/javase/technologies/hotspot/gc/memorymanagement_whitepaper.pdf for background reading. (Hey, we write these things, we might as well encourage people to read them.)

  • Running garbage collector

    How do I run the garbage collector to free memory and delete unused objects?

    Maybe, I'm being stupid, but what has this got to do
    with the garbage collector?The problem is that though you can make the garbage collector run, you can't easily tell it how hard or long to search for collectable objects. The GC makes several passes. First pass is a simply check that will collect only the most obviously collectable objects. So you can tell the gc to run, and it will, but it may miss a lot of the harder objects to collect. (Especially objects whos references are gone, but their location on the stack is active because of another method.)
    So if we could tell the GC, run and don't come back till you get every last objects that is collectable, that would be an excellent thing!
    In my experience, the GC is over agressive and will definitly collect any collectable objects when you manually run the gc.

  • About Garbage Collector

    In Java, there is one system call for garbage collector.
    System.gc();
    I want to know the significance of this system call for GC. Even after calling this method, garbage collector won't get started, still it will run on its own time.
    If this is the thing then what's the significance of this method call?
    Please let me know this.
    Thanking you,
    Ketan

    Addendum
    In a heavy data application, for instance, that stores records in memory for some purpose, then releases that memory and creates next set of records in memory, calling gc really help.
    We have such application where in we tested its performance with and without calling gc. No wonder, we found better results by calling gc.

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

  • Incremental Garbage Collector is halting my server for MINUTES at a time.

    I have a Java server which services hundreds (currently 300-700 on average, target of 2000+) of simultaneous client connections, with a staggering number of long lived (but not permanent) objects.
    The docs for incremental garbage collection state: "The incremental garbage collector, which is off by default, will eliminate occasional garbage-collection pauses during program execution." This is NOT true in my case. During peak load, the Server halts occasionally (once an hour or more) and entire MINUTES tick by. Average wait time is 2.5 - 3.5 minutes, the highest I have seen is 4 minutes, 10 seconds. This is entirely unnacceptable.
    The server is on Red Hat Linux 6.2, kernel 2.2.14-5.0, with a gig of RAM. My current command line options are
    java -server -Xincgc -Xms256M -Xmx900M
    And I have just added -verbose:gc to help analyze the gc performance. I have read the gc tuning guide at http://java.sun.com/docs/hotspot/gc/index.html but still feel rather clueless about what is the optimum setup for my particular application.
    I will of course start experimenting, but I was hoping to find a "wise old elf" who might give some useful pointers to accelerate the process, seeing as how the Server is already running in a production capacity, time is critical.

    Are you using a Java application server like Tomcat, Dynamo, WebLogic etc. ?
    In that case consider running several server instances on the machine, with the applicationserver's software load balancer. Find the amount of RAM allocated to the heap per serverinstance where garbage collection runs takes a couple of seconds, and don't allocate more than this to each server. Start as many servers as you have available RAM for.
    This is the approach recommended by application server vendors such as BEA http://edocs.bea.com/wls/docs61/perform/JVMTuning.html and ATG.
    A side benefit of this approach is that in case you get more concurrent users than your computer can handle, you already have the setup for spreading the load over several computers.

  • 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

  • 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

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

  • Logging Garbage collector for an OC4J with 2JVM

    Hi, I have one OC4J with two JVM setted.
    If I put -verbose:gc it logs in the std Output file.
    I trying to log the garbage collector in two different file each one for one JVM.
    Anyone as an idea?

    Don't create massive amounts garbage memory. It's that simple. You should try to limit the creation of memory inside your animation loop. If there is a process inside the loop that creates memory, there is definitely some way to create that item staticly, rather than allocating new memory with each iteration. There shouldn't be any kind of problem that would involve the creation of THIS much memory, and it's deallocation. If you read about how the garbage collector is implemented, you'll notice that it stores all of it's memory on a single conveyor belt. This is for ALL memory in the program. Therefor once the garbage collector has gone through and marked all of the memory that needs to be reclaimed, it performs it's sweep and must feeze the entire program because that conveyor belt can not be manipulated while it's re-arranging the memory. The garbage collector will eliminate MOST memory leaks, but it does not eliminate any thought on the part of the programmer about memory.
    -Jason Thomas.

  • How to run garbage collector???????

    I have to run garbage collector to enlarge totalmemory during runtime. I added code like System.gc( ), but it did nothing! the totalmemory stayed as before gc run.
    anybody has idea or suggestion?
    thanks a lot

    Are you sure that there are no lingering references to
    your objects. gc can only remove objects which have no
    references to them remaining.No, this is not how garbage collection works in Java. Garbage collection collects unreachable objects, not objects with no references to them.
    To understand the difference, look at this code:
    Vector v = new Vector();
    v.add(v);
    v = new Vector();The original Vector object is unreachable at the end of this code, and is available for garbage collection. This is despite the fact that there exists a reference to the Vector, which is inside the Vector itself.
    Some implementations of garbage collection, such as reference counting, really do collect only objects that have no references to them. Java's garbage collection is superior to these collectors: it collects all unreachable objects.

  • How to make external SWFs garbage collected in Air for iOS?

    My app uses lots of external SWFs( well they are actually included in the app with a folder but they aren't embeded ) and they do not contain any bitmapdata, only vector graphics. The problem I'm having is that they seem to be never garbage collected and System.privateMemory keeps increasing as the app loads more SWFs.
    Since those SWFs only contain vector graphics, I simply nullify all the variables that are holding reference to SWF file and call System.gc().. But it doesn't seem to be working. What would I need to do for the garbage collector to clean the SWFs?
    I'm using Air for iOS 3.5.0.1060 and ActionScript3.0.

    Yes I'm calling System.gc() twice. I tried using loader.unloadAndStop(true) and it seems SWFs are being garbage collected but another problem has surfaced. When repeatedly loading and unloading SWF in a short period, the air garbage collector sometimes fails to work.
    I've tested loading and unloading same SWF 50k times and checked trace.  Occasionally, garbage collector misses to collect garbage like below( swf #45119 is not being garbage collected).
    [UnloadSWF] main.swf/[[DYNAMIC]]/45115
    [UnloadSWF] main.swf/[[DYNAMIC]]/45116
    [UnloadSWF] main.swf/[[DYNAMIC]]/45117
    [UnloadSWF] main.swf/[[DYNAMIC]]/45118
    [UnloadSWF] main.swf/[[DYNAMIC]]/45120
    [UnloadSWF] main.swf/[[DYNAMIC]]/45121

Maybe you are looking for

  • HT3702 My itunes isn't allowing me to purchase the beyonce album. It just sends me over to the support website. What does that mean?

    My itunes isn't allowing me to purchase the beyonce album. It just sends me over to the support website. What does that mean?

  • How can I get a number of items from a group

    I'm trying to load assets into a library. Most of the assets are groups. I'd like to label each asset with number of items from that specific group. Here is my code: var d=app.activeDocument; //create empty library var library = app.libraries.add(Fil

  • Block Particular material for a DC and Plant combo

    Hi All, Iam working for a FMCG client at the movement and i have a peculiar requirement which at the outset seamed easy but iam not able to find a solution. The client wants to block selling of a particular material for specific distribution channel

  • PRTs in IW37N Layout

    We use IW37N to display work order operations.  We'd like to have a PRT field in the layout.  If an operation has one or more PRTs on it, there will be an 'X' in the field, otherwise no 'X'.  IW37N does not seem to have this functionality natively. 

  • Internal Error 1401.

    Hi, I have a function in the backend in a package, which has the spec like this and it is perfectly compiled. PACKAGE SPEC TYPE t_db_bus_unit_tab IS TABLE OF rms_vendor_transfer_control_id.business_unit_id%TYPE INDEX BY BINARY_INTEGER; TYPE t_db_tran