Garbage collector thread

I heard that garbage collector thread runs as a low priority when a java app runs. does anybody know why it runs as a low priority and if it runs as a high priority, what will happen?
Thanks.

First of all there are many different GC implementations - some run in one thread and stop all java threads, some stop all java threads and use multiple threads and one which does most of its work while the java-threads keep running.
However, the GC threads run as far as I know with "normal" priority.
lg Clemens

Similar Messages

  • Garbage collector information

    I read a text like below..
    garbage collector thread informs the object that it is about to be garbage collected
    is it true ?
    what does they want to mean by "inform" ?
    is not it , garbage collector just picks up resource when its no longer used ?
    why inform then ? how they inform also ?

    There are ways of monitoring objects, and doing some additional clean-up (e.g. releasing external resources).
    I think this may refer to the finalize method, which may be called before an object is completely disposed of (there are no guarantees).
    I'd regard finalize as obsolete. If you want to do additional clean up when an object is disposed of, then PhatomReference is probably better.

  • Is garbage collector dameon thread or non dameon thread

    hi,
    i know daemon thread wil do background process. the garbage collector is daemon thread or non daemon thread.

    It is a daemon thread.

  • Garbage collector as daemon thread

    hai
    y is garbage collector made as daemon thread
    what r the primary reasons?

    http://saloon.javaranch.com/cgi-bin/ubb/ultimatebb.cgi?ubb=get_topic&f=1&t=012268
    Are you guys in the same class?
    The Truth About Garbage Collection
    Reference Objects and Garbage Collection
    Garbage collection and performance
    Also, please make the extra effort to write out words such as "why" and "are". The extra keystrokes won't cost much in the way of time, and the enhanced clarity will be appreciated by those communicating on a forum with international readership.
    http://faq.javaranch.com/view?UseRealWords

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

  • Stateless ejb staying live after a garbage collector

    Hi,
    I use an aplication based in struts, in the actions i call session that call cmps, both ejb are stateless.
    Every thing works fine until i make some stress test, when i find that the server (Websphere) stay out of memory. After this i found that my sessions and cmps are staying live after the garbage collector run and i don't know why because the thread already finish and the ejb are stateless.
    Anyone already have this problem, how can i clear the memory of this objects?
    Thanks in advanced
    Ricardo

    Adjust the size of your EJB pool. Just because your application is no longer using the objects doesn't mean that the container won't hang on to them for re-use (object creation is an "expensive" operation).

  • Inefficient garbage collector process - WLS 8.1 SP6 - JVM jdk142_13 (SUN)

    Hi all,
    I am trying to perform some tuning operations in my server (maestroServer_01) because the application uses the total amount of heap size and the garbage collector process is not running fine. The arguments used on this VM are:
    -server -Xms2048m -Xmx2048m -Xss512k -XX:PermSize=384m -XX:MaxPermSize=384m -XX:+UseParallelGC -XX:ParallelGCThreads=4 -XX:+UseAdaptiveSizePolicy -XX:NewRatio=8 -XX:SurvivorRatio=12 -Xverify:none -Xnoclassgc -XX:+DisableExplicitGC -XX:+PrintGCDetails -Dweblogic.webservice.i18n.charset=utf-8 -Duser.timezone=$JAVA_TZ -DejbURL='t3://localhost:9081' -DjpdURL='http://localhost:9081'
    Please let me know if I can change these parameters in the WLS:
    Services -> Bridge -> Messaging Bridge Thread Pool Size -> from 5 to 20
    Configuration -> Tuning -> Socket Readers -> from 33 to 60, and disable "Enable Native IO" option.
    I got some informations from internet about some parameters that can be used to improve the memory utilization of this JVM. The parameters are described in the link below:
    http://java.sun.com/performance/reference/whitepapers/tuning.html
    Does anyone know what can be done? The WLS needs to be restarted every day!
    Thanks!

    yes regularely .. :-) (as you can see from the posts..)
    to your problem, the connectstring seems perfectly valid for a oracle light db installation (which we install within the bpel installation)
    can you check if this polite process is running?
    HTH clemens

  • 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

  • Error "The current garbage collector has no nursery"

    Has anybody any information on the error message "The current garbage collector has no nursery"? We received the following error message after starting the WLS in production mode:
    <2006-jan-25 kl 17:57 CET> <Error> <Management> <BEA-140001> <An error occurred while getting attribute TotalNurserySize on MBean se-i-ld09:Location=se-i-ld09-c01-s01,Name=se-i-ld09-c01-s01,ServerRuntime=se-i-ld09-c01-s01,Type=JRockitRuntime. Method: public long weblogic.t3.srvr.JRockitRuntime.getTotalNurserySize(). Exception: com.bea.jvm.NotAvailableException: The current garbage collector has no nursery..
    com.bea.jvm.NotAvailableException: The current garbage collector has no nursery.
         at jrockit.management.jvm.GarbageCollectorImpl.getNurserySize()J(Unknown Source)
         at weblogic.t3.srvr.JRockitRuntime.getTotalNurserySize()J(JRockitRuntime.java:112)
         at jrockit.reflect.NativeMethodInvoker.invoke0(Ljava.lang.Object;ILjava.lang.Object;[Ljava.lang.Object&amp)Ljava.lang.Object;(Unknown Source)
         at jrockit.reflect.NativeMethodInvoker.invoke(Ljava.lang.Object;[Ljava.lang.Object&amp)Ljava.lang.Object;(Optimized Method)
         at jrockit.reflect.VirtualNativeMethodInvoker.invoke(Ljava.lang.Object;[Ljava.lang.Object&amp)Ljava.lang.Object;(Optimized Method)
         at java.lang.reflect.Method.invoke(Ljava.lang.Object;[Ljava.lang.Object;I)Ljava.lang.Object;(Optimized Method)
         at weblogic.management.internal.DynamicMBeanImpl.getAttribute(Ljava.lang.String&amp)Ljava.lang.Object;(DynamicMBeanImpl.java:574)
         at com.sun.management.jmx.MBeanServerImpl.getAttribute(Ljava.lang.Object;Ljava.lang.String&amp)Ljava.lang.Object;(MBeanServerImpl.java:1183)
         at com.sun.management.jmx.MBeanServerImpl.getAttribute(Ljavax.management.ObjectName;Ljava.lang.String&amp)Ljava.lang.Object;(MBeanServerImpl.java:1153)
         at weblogic.management.internal.RemoteMBeanServerImpl.getAttribute(Ljavax.management.ObjectName;Ljava.lang.String&amp)Ljava.lang.Object;(RemoteMBeanServerImpl.java:287)
         at weblogic.management.internal.RemoteMBeanServerImpl_WLSkel.invoke(ILweblogic.rmi.spi.InboundRequest;Lweblogic.rmi.spi.OutboundResponse;Ljava.lang.Object&amp)Lweblogic.rmi.spi.OutboundResponse;(Unknown Source)
         at weblogic.rmi.internal.BasicServerRef.invoke(Lweblogic.rmi.extensions.server.RuntimeMethodDescriptor;Lweblogic.rmi.spi.InboundRequest;Lweblogic.rmi.spi.OutboundResponse&amp)V(BasicServerRef.java:477)
         at weblogic.rmi.internal.BasicServerRef$1.run()Ljava.lang.Object;(BasicServerRef.java:420)
         at weblogic.security.acl.internal.AuthenticatedSubject.doAs(Lweblogic.security.subject.AbstractSubject;Ljava.security.PrivilegedExceptionAction&amp)Ljava.lang.Object;(AuthenticatedSubject.java:363)
         at weblogic.security.service.SecurityManager.runAs(Lweblogic.security.acl.internal.AuthenticatedSubject;Lweblogic.security.acl.internal.AuthenticatedSubject;Ljava.security.PrivilegedExceptionAction&amp)Ljava.lang.Object;(SecurityManager.java:144)
         at weblogic.rmi.internal.BasicServerRef.handleRequest(Lweblogic.rmi.spi.InboundRequest&amp)V(BasicServerRef.java:415)
         at weblogic.rmi.internal.BasicExecuteRequest.execute(Lweblogic.kernel.ExecuteThread&amp)V(BasicExecuteRequest.java:30)
         at weblogic.kernel.ExecuteThread.execute(Lweblogic.kernel.ExecuteRequest&amp)V(ExecuteThread.java:219)
         at weblogic.kernel.ExecuteThread.run()V(ExecuteThread.java:178)
         at java.lang.Thread.startThreadFromVM(Ljava.lang.Thread&amp)V(Unknown Source)>
    Thanks in advance for your help - it is much appreciated!
        Cheers, Jonas                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

    This exception is thrown by the JRockit Management API when querying the nursery size of a GC that has no nursery (single-generational GC). The logical place to catch the error would be in the weblogic.t3.srvr.JRockitRuntime.getTotalNurserySize() method, which implies that it is a WLS issue.
    Maybe it has been fixed in a later WLS 8.1 service pack?
    If you run with a generational GC, i.e. "-Xgc:gencon" the error will go away, but that has larger implications on the behavior of your app so it should not be used as a workaround.

  • 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( NOT ACTIVATING)

    I AM CERTIFIED, LEARNED IN THE COURSE THAT THE GARBAGE COLLECTOR IS A SYSTEM THREAD WHICH RUNS AND COLLECTS ALL THE UN-REFERENCED OBJECTS BUT I COULDN'T MANAGED TO ACTIVATE IT:
    THE PROBLEM IS DEFINED AS FOLLOWS:-
    1. WE KNOW THAT IF WE OVERRIDE THE FINALIZE METHOD OF AN OBJECT THEN IT IS CALLED WHEN THE SPECIFIC OBJECT IS GARBAGE COLLECTED.
    THATS WHY I OVERRIDED A CLASS'S FINALIZE METHOD AND ISSUED A PRINTLN STATEMENT
    2. THEN AT RUNTIME I INSTANTIATED THE OBJECT OF THAT PARTICULAR CLASS .
    3. I SET THE REFERENCE TO NULL.( AT RUNTIME )
    4. NOW ACCORDING TO THE DOCUMENTATION THE OBJECTED SHOULD BE GARBAGE COLLECTED AFTER SOMETIME BUT I WAITED FOR A ABOUT TEN MINUTES BUT IT ISN'T.
    PLEASE ANSWER THIS QUESTION AN IF POSSIBLE EXPLAIN THE MECHANISM BY WHICH THE FINALIZE METHOD IS CALLED AT RUNTIME
    IT SHOULD BE NOTED THAT THIS THREAD RUNS IN LOW MEMORY CONDITIONS BUT SINCE IT IS A LOW PRIORITY THREAD HOW CAN IT MANAGES TO RUN IN LOW MEMORY CONDITIONS

    The only purpose finalize should be used for is a last ditch effort to free resources other than memory allocation. That said...
    -It should NEVER be used to free a resource that is not automatically freed when the application exits. So for example it could be used to close a socket, but it should not exist when the 'resource' is a file.
    -It should NEVER be the only way to free a resource. There is a reason I said "last ditch". The user of the object should have an explicit method to call which frees the resources.
    And that said I would never use it regardless even for a last ditch cleanup. The reason for that is that it would tend to hide the improper usage of the class - in other words that the user wasn't calling the correct clean up method. I might use it to put a diagonistic (probably an unchecked exception) which indicates that the resource was not cleaned.
    Expanding further on the other comments made here, if you read the spec you will find that the language does not guarantee that finalize will be called. All that it guarantees is that if it is called it will only be called once. In addition finalize can reduce performance because the existance of it might (and probably will) force the garbage collector to do two passes on the object rather than just one.

  • Garbage Collector in JC 2.2

    Help: I am trying to understand how a Passive Garbage Collector (GC) implementation works in Java Card v2.2. As I understand it, Java Card vendors have the option to implement Automatic GC or a Passive GC under version 2.2 or higher.
    My question is as follows:
    What if object X no longer used, and was instantiate during the install() process:
    With Automatic GC: the GC would automatically reclaim memory after the process() method finish executing. If object X has no other references. Also, any other objects without any references would be reclaimed as well.
    With Passive GC: In the process() method the developer must call requestObjectDelete(), and before the next APDU request, the JCRE would reclaim memory. Is this right?
    What happens requestObjectDelete() is called on an object that still has references? Does it still reclaim it? In either Passive or Automatic GC?
    Do any vendors supporting Automatic GC? How about Java Card version 2.2.2?
    Thank you for any help
    Maguar

    What happens requestObjectDelete() is called on an object that still has references? Until now I haven't seen a method called "requestObjectDelete()" (and Google, too).
    Are you probably referring to the static method JCSystem.requestObjectDeletion() ?
    This method can not be called "on an object". It only allows to explicitly invoking the GC for freeing the memory allocated by objects that can not be accessed anymore.
    This solves the problem that current JavaCards are not multi-threaded. Therefore the GC can not be started in background as it does in the J2SE environment.
    By calling JCSystem.requestObjectDeletion() a JavaCard applet "voluntary" gives away CPU time to the GC. In single threaded environments this means that the caller (the JavaCard applet) is halted until the GC has finished its work.
    Jan

  • Garbage Collector behaviour

    It seems that the only requirement of a garbage collector is that it must cleanup some unreferenced objects when the system is low in memory. Aside from that, is there anywhere that documents in some detail what the garbage collector will actually do for a specific version of the VM, specifically 1.3.1?
    I am interested in knowing:
    1) Does the GC periodically run cleanups? If so, when? Does it cleanup all unreferenced objects, or only some? How does it decide? etc.
    2) How does the GC respond to calls to System.gc()? Will it do a thorough cleanup or half-hearted? Will it cleanup right away? etc.
    3) Is there any delay between marking an object for cleanup and running the finalize method?
    4) How does the GC respond to calls to Runtime::runFinalization()?
    Thanks,
    -Brian

    1) Does the GC periodically run cleanups?Basically yes.
    If so, when?Randomly. It isn't defined. When the JVM starts to run down with memory, gc will more likely run, but it's not guaranteed.
    Does it cleanup all unreferenced objects, or only some?Randomly; It runs in a background thread, and may stop frequently.
    2) How does the GC respond to calls to System.gc()?It'll schedule it to run, but nothing guarantees that it actually will run.
    Will it cleanup right away?Definitely not. Maybe it'll start it, it even possible that it'll do all of it, but equivalently possible that won't cleanup anything. No way to tell.
    3) Is there any delay between marking an object for
    cleanup and running the finalize method?Yup, the delay might be anything from almost zero to infinite time.
    It is even possible that your program stops before the gc would ever
    finalized one single object.
    4) How does the GC respond to calls to
    Runtime::runFinalization()?Well, this is a weak request that you're going to run finalizations, but
    nothing will guarantee that it actually will happen.
    The best you can do is never provide finalize() methods, and even if you do, do not trust that they'll ever run!
    The only advise I can give: forget that such animal as "garbage collector" exists.

  • Garbage collector - controlling it

    The main performance problem on our website right now is from the garbage collector. Yes, our site is very 'thick', but the gc locks out other threads for 10 seconds or so regularly, and once a day or locks it up for several MINUTES. The main problem is that we have a few very large objects that never go away, but the gc still has to occasionally scan them.
    I developed a way to put the two GarbageCollector threads (per vm) into the lowest priority. I've seen documentation that this is where they are supposed to be anyway, but they are really at the normal level with everything else. This works great on NT, but only works ok on Solaris. On NT, the gc still pegs the cpu, but other threads are almost unnaffected.
    Anyway, my bosses are concerned about this fix, wondering what negative impact it will have or if the gc won't get enough time or whatever.
    I just wondered what you all think of this fix. Has anyone else tried it?
    Also, does anyone know of a way to tell the gc not to every scan certain objects?

    You can also try the incremental and concurrent garbage collectors. These are enabled with the -Xincgc and -Xconcgc options to the java command, respectively. They may have lower performance overall, but generally have much shorter GC pause times.
    Of course, don't forget the top tip for improving GC performance is always not to create unnecessary objects!

  • Can someone explain how garbage collector works in this program ?

    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!");
    } ///:~
    This code is From Bruce Eckel's "thinking in Java"
    Here is what I understand and what I don't
    At a certain point during the execution of the while loop (in the method main), the garbage collector kicks in and will call the method finalize() -
    I am at a loss as to what happens afterwards -
    Do the chairs continue to get created (which means the variable i keeps incrementing) and the finalize method keep getting called (which means finalized keeps incrementing) till the system realizes it is really low on memory and starts reclaiming memory ie i now starts decrementing ?
    What I would like to know is the exact flow or execution of the code after the garbage collector starts kicking in ie. what happens to the variables "i" (does it increment and then decrement), "created" (does it keep incrementing ), "finalized" (does it keep incrementing) and when is the if i==47{ } statement within finalize() get executed.
    There is no part of the code where i is being decremented (so I am guessing that it is the garbage collector reclaiming object memory that must be decrementing it).
    I am really confused -unfortunately there's very little in the book that really explains the flow of execution after the garbage collector kicks in and finalize() is called.
    Any help would be greatly appreciated

    Nice example, but Bruce chose some suboptimal names, I think.
    "i" can be thought of as the "ID" of a given Chair (note that it is not static). It is neither incremented nor decremented - it's just assigned from "created". This lets us identify specific chairs (like, say, "Chair #47").
    "created" is a running total of the number of times the Chair constructor has been called.
    "finalized" is a running total of the number of Chairs that have been finalized.
    The process starts creating Chairs as fast as it can. Eventually, memory gets low, and gc() starts collecting Chairs. While that's happening, chairs are still being created in the main Thread. So "created" and "finalized" may both be incrementing at the same time.
    When gc() picks Chair#47, the finalizer code sets a flag that causes new Chairs to stop being created. This causes the program to fall out of the while() loop, and the program spits out its data and exits.
    On my machine, the program created 29,542 chairs before exiting.
    Remember - often, gc() runs only when/if the JVM decides it's running low on memory. Specifics depend on the JVM and the startup options you use - some JVMs are very, very clever about doing incremental garbage-collection these days.
    Does that make more sense?
    Grant
    (PS - it's very, very good that you posted a working code sample. But learn about the \[code\] and \[code\] tags, please - makes your sample WAY easier to read...)

Maybe you are looking for

  • Kernel Panic when I Use the Internet

    My kernel panics any time I try to connect to a page with Firefox, use pacman (I can use pacman for searching native packages and removing them, but I can't update or get new packages), etc. I can ping websites, and I'm connected to the internet, but

  • HOW to install Boot Camp/Windows XP

    WOW am I confused. I go out and buy MacBook Pro and a brand new full version of Windows XP and I can't get past first base. I have downloaded Boot Camp and am at the screen where it wants me to select a destination volume to install it to and I have

  • IPad4 - How do I delete ALL (12K ) emails in one go??

    IPad4 - How do I delete ALL (12K ) emails in one go??

  • Selection screen and authorization check for plant from 2 diff tables?

    Hi, Could anyone help me out? how to write code for  this? u2022   Fields for selection Plant : WERKS (one selection) - check authorization access u2013 Mandatory . Material code MATNR (one selection) - Mandatory and while doing the authorization che

  • Printing and Exporting to Powerpoint

    Hello, I'm a relatively new user of Xcelsius and hoping someone could guide me through the problems I have come across. First -  Printing:  I've exported the Dashboard I created using Adobe and now looking to print it.  For some reason, when I print