Garbage Collection facilitation by assigning variables to null

Hello,
I understand Garbage Collection (GC) can be facilitated by assigning variables to null. Is this true for all variables?
I have a class and there are some member variables which are strings. Also i have some methods with some string variables declared and defined inside the method. I am assigning null to class member variables and also the string variables of the method.
is it correct to assign null and faciliate GC for the string variables declared and defined inside the method?
Class A {
String t1;
public void test() {
String t2 = "test";
// processing
t2 = null; // Will this facilitate GC?
public static void main (String[] args) {
test();
A obj = new A();
A.t1 = "testclass";
A.t1 = null; // Will this faciliate GC?
Thanks, Aravinth

In fact, the java heap is divided into a space for new allocations, and two survivor spaces. The algorithm for when collection occurs in each space is complex, and tuning GC is an interesting topic all its own. Follow the best advice you have been given ... chillax. The JVM has GC under control.
<think/> Of course, having said this, you can have memory leaks if you create references that never go out of scope, even if they are no longer used. Avoid this.
� {�                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

Similar Messages

  • Garbage collection – local variable

    I have a doubt in garbage collection.
    Please look int the below code.
    I hope that even if i didn't make myLocalVar = null; , i believe that garbage collection happens immediately,
    Please let me know am i right ?
    void method() {
      MyClass myLocalVar = null;
      try {
        myLocalVar = get_reference_to_object();
        //.. do more here ...
      } finally {
        if (myLocalVar != null) {
          myLocalVar.close(); // it is resource which we should close
        myLocalVar = null; // THIS IS THE LINE I AM TALKING ABOUT
    }

    JEisen wrote:
    es5f2000 wrote:
    I'm pretty sure that there's no guarantee that GC will run at termination time. That's what causes the issue with finalize(). It is theoretically possible to start a program, run it, and cleanly terminate it without getting a GC.True. I meant more that memory will be freed when the program terminates, not necessarily garbage collected. :)
    I just read about the finalize() gotcha -- never knew that. So is it possible for a program to exit without releasing I/O resources if they were being closed in finalize()?Yes and no.
    The basic answer is yes, however when the VM quits from an OS level the handles/locks/etc that were being used by the VM will, god willing, be released.
    A better example though is something like JDBC where you have remote resources waiting on a signal to be released. Having clean up code in finalize could well never be called and in that case the remote resources would be held on to.

  • Garbage collecting threads

    I am doing the following:
    public class MyClass {
         private Thread t = null;
         public class testThread extends Thread{
           public void run(){
                  String logName = this.getClass().getName();
                  Logger.Print( logName );  // Basically prints logName to file
                  for( int i = 1; i<4; i++){
                         try{
                           Thread.sleep(100)
                           [do stuff]
                           Thread.sleep(100);
                         catch(InterruptedException e) { }
           public callThread(){
               if ( t != null ){
                        if( !(t.isAlive()){
                               t = new TestThread();
                               t.start();
               else{
                               t = new TestThread();
                               t.start();
    } What, I want to happen is a thread to finish and after that a new one to start, and once the old thread does not have any variable assoiciated to it anymore, it should get garbage collected as far as my java understnading goes, this is exactly what should happen, in duo time whenever the garabage collecter decides so. This is a very long time running program.
    And the log shows the names of the threads like Thread-1 , Thread-2, Thread-3 , Thread-4, basically this name is increased by one everytime the function callThread is called and the old thread finished running, is there a limit to how many times I can call it like if it is called 10 billion times, will I have Thread-10000000000 in my log? and will the garbage collection work as I think? I am a c++ programmer so I do not trust it 100%, I really feel like adding delete t; so I can feel confident it is really gone before I do a t = new TestThread(); hehe C++ sickness??
    Please give me advice on this!!! and I will be very happy!
    Edited by: dakiar on Mar 19, 2008 8:18 AM

    dakiar wrote:
    What, I want to happen is a thread to finish and after that a new one to start,Use join(), rather than looping and checking isAlive, in order to determine when a thread has died.
    while (true) {
      Runnable r = new MyRunnable(); // You have no reason to extend Thread. It's preferable to implement runnable.
      Thread t = new Thread(r);
      t.start();
      t.join();
    and once the old thread does not have any variable assoiciated to it anymore, it should get garbage collected as far as my java understnading goes,It will become eligible for GC. There's no guarantee when or even if it will actually be GCed, other than that GC will at least happen before OutOfMemoryError.
    And the log shows the names of the threads like Thread-1 , Thread-2, Thread-3 , Thread-4, basically this name is increased by one everytime the function callThread is called and the old thread finished running, is there a limit to how many times I can call it No.
    like if it is called 10 billion times, will I have Thread-10000000000 in my log? Perahps. Or if Thread uses an int then it might wrap around to Integer.MIN_VALUE and give Thread--2147483648.
    You know you can assign your own names to the Threads.
    and will the garbage collection work as I think? It will work fine, and that has nothing to do with thread names.
    I am a c++ programmer so I do not trust it 100%,So, you think that you managing memory ad-hoc in every program you write when you're trying to focus on implementing the business requirements of your app will be better at it than the guys who were specifically focussed on writing memory management that would be handled consisently by the computer, and has been continuously refined, not to mention tested by thousands of Java developers over the last dozen or so years?
    I really feel like adding delete t; You can't and you don't need to.

  • Nested object reference after garbage collection

    I have a question about how GC works.
    Assume I have a Class A which has a reference to class B inside it. I create a object of class B and assign to member variable of class A.
    Now when obja is no longer needed, I set it null. And when GC runs, the object will be removed from memory. But should I also need to explicitly set objb to null. If i don't set it, will it also get garbage collected when obja is being removed from memory?
    public class ClassA {
    private ClassB objB = new ClassB();
    private static void main(String args[]) {
    ClassA obja = new ClassA();
    obja = null;
    }

    801625 wrote:
    But should I also need to explicitly set objb to null.No.
    If i don't set it, will it also get garbage collected when obja is being removed from memory?If there are no other references outside of classA to the object referenced by objB (in your case an instance of ClassB) then it will be garbage collected.
    Note - the only time one needs to set a reference to null is if one wants the object it references to be eligible for GC before the reference goes out of scope. There is a slight complication to this - depending on the JVM implementation, if a reference is defined in a block internal to a method then even though it goes out of scope when execution goes out of the block anything it references may not be eligible for GC until the method exits.

  • IncompatibleClassChangeError. Caused by garbage collection?

    The problem occurs on JDK 1.3.1-b24 compiled in JBuilder Windows and
    running on Sun Solaris with identical JDK version.
    The application is a relatively complex RMI server.
    An error recovery function in the server runs in a Thread every two
    minutes. Most of the time it has nothing to do and ends without
    incident.
    Occasionally conditions require recovery that may not be successful
    for many attempts.
    Part of the recovery is a simple debug display of parameters involved
    in the recovery. There will be multiple displays during a single
    recovery cycle.
    In a recent example of problem, the recovery executed every two
    minutes for over two hours with the debug display working
    successfully.
    Suddenly one display works successfully and 5 milliseconds later the
    same display fails with a IncompatibleClassChangeError.
    The last part of the stack trace is:
    java.lang.IncompatibleClassChangeError
         at [class name].toString([class name].java:74)
         at java.lang.String.valueOf(String.java:1947)
         at java.lang.StringBuffer.append(StringBuffer.java:370)
         at java.util.AbstractMap.toString(AbstractMap.java:567)
         at java.lang.String.valueOf(String.java:1947)
    line 74 of class is
    public String toString()
    return _responses.toString();
    where _responses is an ArrayList that has been stored on Map that
    contains the parameters that is being display as part of the debug
    information.
    Once the failure occurs, it will always occur until the JVM is
    restarted. This suggests to me that something in the JVM, maybe garbage collection, has either corrupted the in-memory copy of the class or some internal table used by the JVM has become corrupted.
    Anybody else have ideas?

    java.lang.IncompatibleClassChangeError
         at [class name].toString([class name].java:74)
         at java.lang.String.valueOf(String.java:1947)
    at
    java.lang.StringBuffer.append(StringBuffer.java:370)
    at
    java.util.AbstractMap.toString(AbstractMap.java:567)
         at java.lang.String.valueOf(String.java:1947)
    Problem: The IncompatiableClassChangeError is a Symbolic resolution problem. In lamen's terms a package,class,method,or a variable name is corrupted.
    Possible problem location: Are you using a Custom ClassLoader? Do you Load and compile on the fly?
    where _responses is an ArrayList that has been stored
    on Map that
    I would look hard at the following methods in your MAP Interface:
    public void clear();
    public Object put(Object key,Object value);
    public void putAll(Map t);
    public Object remove(Object key);Is it possible that your MAP interface is corrupting your ArrayList using one of the above methods? Then, when you are building the strings using the AbstractMap's.toString() method, you are getting the IncompatiableClassChangeError?
    This is word for word listing of the MAP Interface...V1.41.
    Some map implementations have restrictions on the keys and values they may contain. For example, some implementations prohibit null keys and values, and some have restrictions on the types of their keys.
    This puzzles me
    Attempting to insert an ineligible key or value throws an unchecked exception, typically NullPointerException or ClassCastException.
    What's this, they state above that you should get a unchecked Exception, but the first sentence below makes me assume they are pulling a query on an ineligible key or value???
    Attempting to query the presence of an ineligible key or value may throw an exception, or it may simply return false; some implementations will exhibit the former behavior and some will exhibit the latter.
    Oh,OK. They are basically saying it totally depends on how you implement this Interface <grin>
    More generally, attempting an operation on an ineligible key or value whose completion would not result in the insertion of an ineligible element into the map may throw an exception or it may succeed, at the option of the implementation.
    The "optional" they are talking about are the methods that I listed above.
    Such exceptions are marked as "optional" in the specification for this interface.
    Well you asked for ideas, so there's a brain fart for you?
    ...Hope this helps

  • Remove / unload external swf file(s) from the main flash file and load a new swf file and garbage collection from memory.

    I can't seem to remove / unload the external swf files e.g when the carousel.swf (portfolio) is displayed and I press the about button the about content is overlapping the carousel (portfolio) . How can I remove / unload an external swf file from the main flash file and load a new swf file, while at the same time removing garbage collection from memory?
    This is the error message(s) I am receiving: "TypeError: Error #2007: Parameter child must be non-null.
    at flash.display::DisplayObjectContainer/removeChild()
    at index_fla::MainTimeline/Down3()"
    import nl.demonsters.debugger.MonsterDebugger;
    var d:MonsterDebugger=new MonsterDebugger(this);
    stage.scaleMode=StageScaleMode.NO_SCALE;
    stage.align=StageAlign.TOP_LEFT;
    stage.addEventListener(Event.RESIZE, resizeHandler);
    // loader is the loader for portfolio page swf
    var loader:Loader;
    var loader2:Loader;
    var loader3:Loader;
    var loader1:Loader;
    //  resize content
    function resizeHandler(event:Event):void {
        // resizes portfolio page to center
    loader.x = (stage.stageWidth - loader.width) * .5;
    loader.y = (stage.stageHeight - loader.height) * .5;
    // resizes about page to center
    loader3.x = (stage.stageWidth - 482) * .5 - 260;
    loader3.y = (stage.stageHeight - 492) * .5 - 140;
    /*loader2.x = (stage.stageWidth - 658.65) * .5;
    loader2.y = (stage.stageHeight - 551.45) * .5;*/
    addEventListener(Event.ENTER_FRAME, onEnterFrame,false, 0, true);
    function onEnterFrame(ev:Event):void {
    var requesterb:URLRequest=new URLRequest("carouselLoader.swf");
    loader = null;
    loader = new Loader();
    loader.name ="carousel1"
    //adds gallery.swf to stage at begining of movie
    loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, ioError);
    function ioError(event:IOErrorEvent):void {
    trace(event);
    try {
    loader.load(requesterb);
    } catch (error:SecurityError) {
    trace(error);
    addChild(loader);
    loader.x = (stage.stageWidth - 739) * .5;
    loader.y = (stage.stageHeight - 500) * .5;
    // stop gallery.swf from duplication over and over again on enter frame
    removeEventListener(Event.ENTER_FRAME, onEnterFrame);
    //PORTFOLIO BUTTON
    //adds eventlistner so that gallery.swf can be loaded
    MovieClip(root).nav.portfolio.addEventListener(MouseEvent.MOUSE_DOWN, Down, false, 0, true);
    function Down(event:MouseEvent):void {
    // re adds listener for contact.swf and about.swf
    MovieClip(root).nav.info.addEventListener(MouseEvent.MOUSE_DOWN, Down1, false, 0, true);
    MovieClip(root).nav.about.addEventListener(MouseEvent.MOUSE_DOWN, Down3, false, 0, true);
    //unloads gallery.swf from enter frame if users presses portfolio button in nav
    var requester:URLRequest=new URLRequest("carouselLoader.swf");
        loader = null;
    loader = new Loader();
    loader.name ="carousel"
    loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, ioError);
    function ioError(event:IOErrorEvent):void {
    trace(event);
    try {
    loader.load(requester);
    } catch (error:SecurityError) {
    trace(error);
    addChild(loader);
    loader.x = (stage.stageWidth - 739) * .5;
    loader.y = (stage.stageHeight - 500) * .5;
    removeChild( getChildByName("about") );
    removeChild( getChildByName("carousel1") );
    // remove eventlistner and prevents duplication of gallery.swf
    MovieClip(root).nav.portfolio.removeEventListener(MouseEvent.MOUSE_DOWN, Down);
    //INFORMATION BUTTON
    //adds eventlistner so that info.swf can be loaded
    MovieClip(root).nav.info.addEventListener(MouseEvent.MOUSE_DOWN, Down1, false, 0, true);
    function Down1(event:MouseEvent):void {
    //this re-adds the EventListener for portfolio so that end user can view again if they wish.
    MovieClip(root).nav.portfolio.addEventListener(MouseEvent.MOUSE_DOWN, Down, false, 0, true);
    MovieClip(root).nav.about.addEventListener(MouseEvent.MOUSE_DOWN, Down3, false, 0, true);
    var requester:URLRequest=new URLRequest("contactLoader.swf");
    loader2 = null;
    loader2 = new Loader();
    loader2.name ="contact"
    loader2.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, ioError);
    function ioError(event:IOErrorEvent):void {
    trace(event);
    try {
    loader2.load(requester);
    } catch (error:SecurityError) {
    trace(error);
    addChild(loader2);
    loader2.x = (stage.stageWidth - 658.65) * .5;
    loader2.y = (stage.stageHeight - 551.45) * .5;
    // remove eventlistner and prevents duplication of info.swf
    MovieClip(root).nav.info.removeEventListener(MouseEvent.MOUSE_DOWN, Down1);
    //ABOUT BUTTON
    //adds eventlistner so that info.swf can be loaded
    MovieClip(root).nav.about.addEventListener(MouseEvent.MOUSE_DOWN, Down3, false, 0, true);
    function Down3(event:MouseEvent):void {
    //this re-adds the EventListener for portfolio so that end user can view again if they wish.
    MovieClip(root).nav.portfolio.addEventListener(MouseEvent.MOUSE_DOWN, Down, false, 0, true);
    MovieClip(root).nav.info.addEventListener(MouseEvent.MOUSE_DOWN, Down1, false, 0, true);
    var requester:URLRequest=new URLRequest("aboutLoader.swf");
    loader3 = null;
    loader3 = new Loader();
    loader3.name ="about"
    loader3.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, ioError);
    function ioError(event:IOErrorEvent):void {
    trace(event);
    try {
    loader3.load(requester);
    } catch (error:SecurityError) {
    trace(error);
    addChild(loader3);
    loader3.x = (stage.stageWidth - 482) * .5 - 260;
    loader3.y = (stage.stageHeight - 492) * .5 - 140;
    removeChild( getChildByName("carousel") );
    removeChild( getChildByName("carousel1") );
    // remove eventlistner and prevents duplication of info.swf
    MovieClip(root).nav.about.removeEventListener(MouseEvent.MOUSE_DOWN, Down3);
    stop();

    Andrei1,
    Thank you for the helpful advice. I made the changes as you suggested but I am receiving a #1009 error message even though my site is working the way I wan it to work. I would still like to fix the errors so that my site runs and error free. This is the error I am receiving:
    "TypeError: Error #1009: Cannot access a property or method of a null object reference."
    I'm sure this is not the best method to unload loaders and I am guessing this is why I am receiving the following error message.
         loader.unload();
         loader2.unload();
         loader3.unload();
    I also tried creating a function to unload the loader but received the same error message and my portfolio swf was not showing at all.
         function killLoad():void{
         try { loader.close(); loader2.close; loader3.close;} catch (e:*) {}
         loader.unload(); loader2.unload(); loader3.unload();
    I have a question regarding suggestion you made to set Mouse Event to "null". What does this do setting the MouseEvent do exactly?  Also, since I've set the MouseEvent to null do I also have to set the loader to null? e.g.
    ---- Here is my updated code ----
    // variable for external loaders
    var loader:Loader;
    var loader1:Loader;
    var loader2:Loader;
    var loader3:Loader;
    // makes borders resize with browser size
    function resizeHandler(event:Event):void {
    // resizes portfolio page to center
         loader.x = (stage.stageWidth - loader.width) * .5;
         loader.y = (stage.stageHeight - loader.height) * .5;
    // resizes about page to center
         loader3.x = (stage.stageWidth - 482) * .5 - 260;
         loader3.y = (stage.stageHeight - 492) * .5 - 140;
    //adds gallery.swf to stage at begining of moviie
         Down();
    //PORTFOLIO BUTTON
    //adds eventlistner so that gallery.swf can be loaded
         MovieClip(root).nav.portfolio.addEventListener(MouseEvent.MOUSE_DOWN, Down, false, 0, true);
    function Down(event:MouseEvent = null):void {
    // re adds listener for contact.swf and about.swf
         MovieClip(root).nav.info.addEventListener(MouseEvent.MOUSE_DOWN, Down1, false, 0, true);
         MovieClip(root).nav.about.addEventListener(MouseEvent.MOUSE_DOWN, Down3, false, 0, true);
    //unloads gallery.swf from enter frame if users presses portfolio button in nav
         var requester:URLRequest=new URLRequest("carouselLoader.swf");
         loader = new Loader();
         loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, ioError);
         function ioError(event:IOErrorEvent):void {
         trace(event);
         try {
         loader.load(requester);
         } catch (error:SecurityError) {
         trace(error);
         this.addChild(loader);
         loader.x = (stage.stageWidth - 739) * .5;
         loader.y = (stage.stageHeight - 500) * .5;
    // sure this is not the best way to do this - but it is unload external swfs
         loader.unload();
         loader2.unload();
         loader3.unload();
    // remove eventlistner and prevents duplication of gallery.swf
         MovieClip(root).nav.portfolio.removeEventListener(MouseEvent.MOUSE_DOWN, Down);
    //INFORMATION BUTTON
         //adds eventlistner so that info.swf can be loaded
         MovieClip(root).nav.info.addEventListener(MouseEvent.MOUSE_DOWN, Down1, false, 0, true);
         function Down1(event:MouseEvent = null):void {
         //this re-adds the EventListener for portfolio so that end user can view again if they wish.
         MovieClip(root).nav.portfolio.addEventListener(MouseEvent.MOUSE_DOWN, Down, false, 0, true);
         MovieClip(root).nav.about.addEventListener(MouseEvent.MOUSE_DOWN, Down3, false, 0, true);
         var requester:URLRequest=new URLRequest("contactLoader.swf");
         loader2 = null;
         loader2 = new Loader();
         loader2.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, ioError);    
         function ioError(event:IOErrorEvent):void {
         trace(event);
         try {
         loader2.load(requester);
    }      catch (error:SecurityError) {
         trace(error);
         addChild(loader2);
         loader2.x = (stage.stageWidth - 658.65) * .5;
         loader2.y = (stage.stageHeight - 551.45) * .5;
    loader.unload();
    loader2.unload();
    loader3.unload();
         // remove eventlistner and prevents duplication of info.swf
         MovieClip(root).nav.info.removeEventListener(MouseEvent.MOUSE_DOWN, Down1);
    //ABOUT BUTTON
         //adds eventlistner so that info.swf can be loaded
         MovieClip(root).nav.about.addEventListener(MouseEvent.MOUSE_DOWN, Down3, false, 0, true);
         function Down3(event:MouseEvent = null):void {
         //this re-adds the EventListener for portfolio so that end user can view again if they wish.
         MovieClip(root).nav.portfolio.addEventListener(MouseEvent.MOUSE_DOWN, Down, false, 0, true);
         MovieClip(root).nav.info.addEventListener(MouseEvent.MOUSE_DOWN, Down1, false, 0, true);
         var requester:URLRequest=new URLRequest("aboutLoader.swf");
         loader3 = null;
         loader3 = new Loader();
         loader3.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, ioError);
         function ioError(event:IOErrorEvent):void {
         trace(event);
         try {
         loader3.load(requester);
    }      catch (error:SecurityError) {
         trace(error);
         addChild(loader3);
         loader3.x = (stage.stageWidth - 482) * .5 - 260;
         loader3.y = (stage.stageHeight - 492) * .5 - 140;
         loader.unload();
         loader2.unload();
         loader3.unload();
         // remove eventlistner and prevents duplication of info.swf
         MovieClip(root).nav.about.removeEventListener(MouseEvent.MOUSE_DOWN, Down3);
         stop();

  • SystemManager and Garbage Collection

    Hi everyone, I have a question regarding the SystemManager and Garbage Collection. I have and application that loads in its assets via a swc created in Flash. In that swc I have different MovieClips that act as the different screens of my application each one being tied to its own custom class. For example one MovieClip is a login screen another is the main menu etc. These screens contain components, text fields and animations. The problem that I am having is when I move from one screen to the other the garbage collector is not cleaning up everything. There are still references to the MovieClips that have animations for example. So even though I remove the screen via removeChild and set the variable reference to that object to null it is not releasing the MovieClips. When I pull it up in the profiler it shows me that SystemManager is holding references to them. Also if I debug the applicaion and look inside the instance of the MovieClip I can see that the private property "listeners" has values, but I am not adding listeners. It appears that the SystemManager is adding listeners. Does anyone know how I can clear these listeners or force the SystemManager to release these items. Any ideas or help would be greatly appreciated. I am fairly new to dealing with memory management and garbage collection in Flex. I am using Flash CS4 to create the swc and Flash Builder 4 Beta with the 3.4 framework and Flash Player 10 to create the app. If you need me to clarify any of this please let me know. Again any help or ideas on where to go from here would be great!

    This chain says that the focusManager is referencing UserMenu.  Is there a default button or focusable objects in UserMenu and references from UserMenu to the objects in question?
    BTW, the CS4 fl.managers.FocusManager and any fl.. classes are incompatible with Flex, so make sure you're not using them in your MovieClips.
    Alex Harui
    Flex SDK Developer
    Adobe Systems Inc.
    Blog: http://blogs.adobe.com/aharui

  • Manual garbage collection

    Im running a huge combinatorial generation algorithm and i'm starting to run into memory allocation errors on larger problem instances. I am using the -Xmx256m run time option on the JVM to give it more memory but im generating huge masses off stuff here.
    The question I have is, if I know an object isnt going to be used again is it worth destroying it in memory yourself; i assume if you have some undesired object you can do something like this;
    myObject = null;
    and then call the garbage collector to free up the memory..firstly will this work, secondly what is there performance tradeoff for calling the garbage collector more often and lastly is the garbage collector allready efficient enough that doing things like this is probably not worth it.
    Regards,
    Dave

    Setting references to null MAY help get immediate relief, but its not guarunteed to help. Same with the System.gc() call.
    Doing both those thing will not enable the system to operate with less memory than before, as variables that are out of scope will be discovered during garbage collection, and garbage collection WILL run when the heap is fully utilized.
    Doing the above may make the GC pause lower at the expense of worse performance.
    Instead of doing the above, I'd recommand using the Incremental GC by specifying -Xincgc on the command line. This will run GC more often in the background, leading to shorter GC pauses, but about 10% performance hit in general.
    If OTOH you are running into OutOfMemoryErrors and don't think you should be, you probably have a memory leak. Most likely you are allocating objects and storing them somewhere then forgetting about them. For example, if you stick an object in a HashMap, and then forget about it, that object will not be GC'd, unless the HashMap can be GC'd.

  • Garbage collection

    String string1 = "Test"; 
    String string2 = "Today"; 
    string1 = null; 
    string1 = string2; i want know how many objects have been garbage collected by the JVM in this code .
    is there any function of JVM which can tell me how many have been garbage collected for this code.
    here its a small code. the reason i am asking , for large code it would difficult to track manually for garbages. . so is there any way out ?

    for large code it would difficult to track manually
    for garbages. . so is there any way out ?There is an easy way out: stop worrying about it.
    You don't need to "track" garbage. That's the beauty of garbage collection. It's mostly automatic (as long as you don't do anything silly in your code, such as build a huge data structure, and keep it stored in a global variable forever even though the program will never use the data again.)
    Are you a C++ programmer by any chance? I find that sometimes C++ programmers who run into a garbage collecting system tend to obsess about it needlessly, because so much time and attention has to be spent twiddling with memory allocation in C++.
    How many objects does System.gc() collect? Maybe none. Maybe one. Maybe more. System.gc() might not collect anything at all; it might schedule garbage collection to happen at a later time. There are asynchronous garbage collectors that run in their own threads, collecting whenever the cpu has a few spare cycles. Asking "how many objects are collected at point X in the code" makes no sense on those systems.

  • GUI Garbage Collection

    Hi Everyone.
    This is very urgent. I need to perform a possible garbage collection of a heavy GUI stuff when it is not in use. Each of the GUI stuff is created from an action listener for the various menu items. I did try using WeakReference but its very hard to know that when the collection will take place.
    Here is the code snippet for the situation...
    //this is application's main frame class...
    public class MyApplication extends JFrame
    JMenuItem menu1, menu2;
    WeakReference ref_MyPanel;
    //earlier it was a strong reference of MyPanel over here
    public static void main(String [] args)
    //instantiating this class and showing that here ...
    //This is called from menu1's action listener..
    void showGUI()
    JFrame f = new JFrame();
    if(ref_MyPanel.get()!=null)
    f.getContentPane().add((MyPanel)ref_MyPanel.get());
    else
    MyPanel mp = new MyPanel();
    ref_MyPanel=new WeakReference(mp);
    f.getContentPane().add(mp);
    mp=null;//clearing the strong refernce
    f.show();
    //A GUI class which needs to be reclaimed when done
    class MyPanel extends JPanel
    double [] a;
    MyPanel1()
    a = new double [1000000]; //making the panel instance heavy
    What i want is to reclaim the memory occupied by MyPanel instance after its Frame being closed. I even tried calling the System.gc() from the MyPanel instance's parent frame's WindowListener -> windowClosed() but it didn't help. Actually this is suffering me a lot as there are several menu items and several GUIs are being instantiated similar to those of MyPanel as shown above. Do i need to change this design to achieve the objective?
    Can anyone help?

    We saw a significant memory improvement in our system when we used this
    utility. Try using this handy class to recursively remove each component
    For JFrames & JApplets I think it was
    ComponentCleaner.cleanComponent ( myFrame.getContentPane() );
    For Frames & Applets
    ComponentCleaner.cleanComponent ( myFrame );
    Also, for every addActionListener(), addComponentListener() etc call,
    you want a removeActionListener(), removeComponentListener() call.
    The listeners store references to the visual components if I remember rightly. So avoid anonymous listener classes, and have proper cleanup methods to remove the listeners.
    (code below)
    regards,
    Owen
    import java.awt.Container;
    import java.awt.Component;
    import javax.swing.RootPaneContainer;
    public class ComponentCleaner
        public static void cleanComponent(Component baseComponent)
            if (baseComponent == null) // recursion terminating clause
                return ;
            Container cont;
            Component[] childComponents;
            int numChildren;
            // clean up component containers
            if(baseComponent instanceof Container)
                // now clean up container instance variables
                if (baseComponent instanceof RootPaneContainer)
                   // Swing specialised container
                    cont = (Container)baseComponent;
                    numChildren = cont.getComponentCount();
                    childComponents = cont.getComponents();
                    for(int i = 0;i < numChildren;i++)
                        // remove each component from the current container
                        // each child component may be a container itself
                        cleanComponent(childComponents);
    ((RootPaneContainer)cont).getContentPane().remove(childComponents[i]);
    ((RootPaneContainer)cont).getContentPane().setLayout(null);
    else
    { // General Swing, and AWT, Containers
    cont = (Container)baseComponent;
    numChildren = cont.getComponentCount();
    childComponents = cont.getComponents();
    for(int i = 0;i < numChildren;i++)
    // remove each component from the current container
    // each child component may be a container itself
    cleanComponent(childComponents[i]);
    cont.remove(childComponents[i]);
    cont.setLayout(null);
    } // if component is also a container

  • At which line , Object is Garbage collected.

    1. public class GC {
    2.  private Object o;
    3.   private void doSomethingElse(Object obj) { o = obj; }
    4.   public void doSomething() {
    5.  Object o = new Object();
    6.  doSomethingElse(o);
    7.   o = new Object();
    8.   doSomethingElse(null);
    9  o = null; 10. }
    } When the doSomething method is called, after which line does the Object created in line 5 become available for garbage collection?
    A. Line 5
    B. Line 6
    C. Line 7
    D. Line 8
    E. Line 9
    F. Line 10
    I think it should be line 9.but answer is 8....
    How is it line 8?
    Edited by: user12203354 on Nov 4, 2012 9:38 PM

    You've already ask a similar question in your other thread where I ask you to answer some questions.
    Question on Garbage collection
    You may want to work on one question like this at a time until you understand the difference between an object and a variable that references an object.

  • Garbage Collection in Java

    Hi,
    In the case of Garbage Collection (GM), if I created a object s in line1, done operation in line2 and made s as null in line3 and after some more execution (may be 10000 lines of code or may running of the prog. for 2 days), I will use same var. s again. Will it will able to work or already Garabage Collected ? Can, I get proper answer ?
    bye
    RaviGanesh

    the object referred to by reference "s" becomes a candidate for garbage collection as soon as the last reference to it is broken. so when you make the reference "s" refer to null, if no other references refer to the originat object, the object can be garbage collected. you are free to assign the reference to other objects at any time (supposing you haven't declared the reference final).
    note how careful i was to distinguish "object" from "reference" here. in java, when we say:  Object o = new Object();o is the reference, the new Object is the object. if i then say:  Object p = o;there are now two references to the initially created object, o and p.
    keep in mind the distinction between objects and references to them, and you should be on your way.

  • [JS] $.gc() - garbage collection, etc.

    Hello everyone, bear with me for all the questions.
    $.gc() - Initiates garbage collection in the JavaScript engine.
    Ok, maybe I have a fundamental misunderstanding of things here, but I am wanting to understand a few things:
    I was wanting to know if $.gc() can be called and executed outside of running scripts directly from with in the ESTK toolkit? The reason I ask is that its listed in the tools guide but not the javascript reference. I know things like $.writeln() only seem to apply/display from with in the ETSK toolkit, is it still executed otherwise silently when it appears in a script, $.sleep() works fine when used. So what about $.gc(), can I call it and have it execute from within my scripts outside of running them via the ETSK toolkit?
    Is there a way to test if its in fact being called, executed, working? I have seen people talking about calling it twice and doubling up, $.gc() $.gc(), thus does it even work, or is it just a fabled mythical thing.
    Do codes when executed outside the ETSK toolkit get funneled through the same javascript runtime engine that they do when executing from with in the ETSK toolkit? Is it all the same and the ETSK toolkit is just Adobe's GUI for writing, debugging, targeting different api's for the various programs with in the same underlying engine?
    Does ScriptBay tap into and use this same underlying framework? Does it do anything inherently on its own for garbage collection? (since it can run scripts sequentially, repetitively, etc..)
    Does anyone know what embedded javascript runtime/engine Adobe is using? This would be beneficial for any specific optimizations that can be considered or kept in mind in general based on the specific JS engine thats implemented when coding.
    So aside from the mythical $.gc() , what other best practices for garbage collection should be considered? I know people suggest wrapping your codes in a function, talk of #targetengine (saw in InDesign forum), etc… are there any other common do's and dont's, best practices pertaining specifically to illustrator? Granted I can find a lot about Javascript in general across the web but what about how it applies to Illustrator, its api, limitations, performance, garbage collection, etc..
    Thanks. ;-)
    Again, sorry for all the questions, I am still trying to continue to wrap my head around different aspects of this whole thing. Thanks everyone for any feedback your able to offer and provide. Many thanks in advance, its greatly appreciated. Thanks again.

    I can't answer or help with all of those… Here are my thoughts… The dollar object properties and functions can be called on by script from AI, BR, ID & PS… They are NOT restricted for use in the ESTK tookit. Yeah $.writeln() would write to the console if the toolkit were open if NOT then it will probably launch it… So remove or comment these out. As you can see from $.sleep() it does what it says when run in the host app. #targetengine is exclusive to ID this app can have multi-instances ( or something like that ). The other apps have 1 engine and thats it. AI's engine is persistent so wrapping your code is good practice I do this for BR & PS too… See…
    http://wwwimages.adobe.com/www.adobe.com/content/dam/Adobe/en/devnet/pdf/illustrator/scrip ting/readme_cs5.txt
    As for garbage collection I've never fould the need to use it… I see some like to set variables back to null but again I don't do this…
    You would have been better off asking this question in the ID scripting forum… There are several people there who are better qualified to answer some of this…

  • Swing & Garbage Collection

    If the EventQueue is very active does that starve the garbage collection? Here is the scenario:
    Lets say I have a JFrame that listens for a specific keyboard event. In processing that event a heavy weight JComponent is created and displayed within that frame. If the user, in rapid succession, triggers those key events, and continues to, the allocated memory increases dramatically unitl an out of memory exception occurs.
    Does anyone know if alot of processing is occuring on the Swing EventQueue if that might starve garbage collection?
    Thanks
    Scott

    Firstly, if garbage collection is happening later then you're probably ok. You can't force garbage collection - as long as it gets cleared later the only problem you should ever have is the possibility of some piece of code being slowed slightly by the garbage collector kicking in.
    Secondly, it's best to flush() images before the references are lost. Note that you lose an image reference during your getScaledInstance() line, so you should use a temporary variable to allow you to flush.
    It's been a long time since I looked at Jimi, might you need to perform some sort of cleanup on that canvas before nulling it? I'm also not sure why you're using File and JimiCanvas objects when you can just use the ImageIcon(String) constructor to load the image in one line and reduce the risk of introducing errors.

  • API for Garbage Collection

    We are using WLS 6.1 SP3 on a Solaris machine. Is there any API we can use to
    automate garbage collection instead of manually doing through the Admin Console.
    Thanks in advance.

    I can't answer or help with all of those… Here are my thoughts… The dollar object properties and functions can be called on by script from AI, BR, ID & PS… They are NOT restricted for use in the ESTK tookit. Yeah $.writeln() would write to the console if the toolkit were open if NOT then it will probably launch it… So remove or comment these out. As you can see from $.sleep() it does what it says when run in the host app. #targetengine is exclusive to ID this app can have multi-instances ( or something like that ). The other apps have 1 engine and thats it. AI's engine is persistent so wrapping your code is good practice I do this for BR & PS too… See…
    http://wwwimages.adobe.com/www.adobe.com/content/dam/Adobe/en/devnet/pdf/illustrator/scrip ting/readme_cs5.txt
    As for garbage collection I've never fould the need to use it… I see some like to set variables back to null but again I don't do this…
    You would have been better off asking this question in the ID scripting forum… There are several people there who are better qualified to answer some of this…

Maybe you are looking for

  • Move up one level in path and make new folder

    How do I get applescript to make a new folder one level up from myFolder i.e. set myFolder to ¬ (choose folder with prompt "Where are the image files for which you want to change exif data ?") as reference make new folder at myFolder with properties

  • Printing Problem on IE10

    I'm using Visual Studio 2010 with Crystal Report for VS 13_0_13 on Windows 7.  I create a bunch  of Crystal Report but when I try to print them nothing happen.  The Print Dialog screen also weird, non of the boxes has any setting and there are no pre

  • Acrobat PDFmaker is ignoring hard page breaks in Word docx

    I'm working with a client's Word docx file which is formatted almost entirely with tables and uses hard page breaks throughout. When the document is exported to a PDF using Acrobat PDFMaker, some of the hard page breaks are rendered but some of them

  • Why I can't change my country?

    Why I can't change my country?

  • Imported ID pdfs appearance alters when imported into Quark as picture

    Can anyone tell me why Indesign created pdf's change when imported into a quark picture box? I receive ads from various companies for a magazine in hi-rez pdf formats and when imported the appearance changes to include all the components/elements/box