Page 2 of 2 FirstFirst 12
Results 21 to 31 of 31
Like Tree7Likes

Thread: JScrollPane not finalizing

  1. #21
    RocketRod9 is offline Member
    Join Date
    Feb 2012
    Posts
    11
    Rep Power
    0

    Default Re: JScrollPane not finalizing

    According to JavaDocs, all Classes derive from java.lang.Object, and since java.lang.Object has a finalize method ALL Classes have an inherited finalise method.

    To back me up, here is an extract from JavaWorld explaining 'GC':

    "every class inherits the finalize() method from java.lang.Object
    the method is called by the garbage collector when it determines no more references to the object exist
    the Object finalize method performs no actions but it may be overridden by any class
    normally it should be overridden to clean-up non-Java resources ie closing a file
    if overridding finalize() it is good programming practice to use a try-catch-finally statement and to always call super.finalize() (JPL pg 47-48). This is a saftey measure to ensure you do not inadvertently miss closing a resource used by the objects calling class
    protected void finalize() throws Throwable {
    try {
    close(); // close open files
    } finally {
    super.finalize();
    }
    }
    any exception thrown by finalize() during garbage collection halts the finalization but is otherwise ignored
    finalize() is never run more than once on any object"

    Here is an example from the same publication:
    "/** Example shows garbage collector in action
    Note that the finalize() method of object GC1
    runs without being specifically called and that
    the id's of garbage collected objects are not
    always sequential.
    */

    class TestGC {

    public static void main(String[] args) {

    Runtime rt = Runtime.getRuntime();

    System.out.println("Available Free Memory: " + rt.freeMemory());

    for(int i=0; i<10000; i++ ) {
    GC1 x = new GC1(i);
    }

    System.out.println("Free Memory before call to gc(): " +
    rt.freeMemory());
    System.runFinalization();
    System.gc();
    System.out.println(" Free Memory after call to gc(): " +
    rt.freeMemory());

    }
    }

    class GC1 {

    String str;
    int id;

    GC1(int i) {
    this.str = new String("abcdefghijklmnopqrstuvwxyz");
    this.id = i;
    }

    protected void finalize() {
    System.out.println("GC1 object " + id + " has been finalized.");
    }

    }"

    In particular, it uses the same method I used to see if my Objects were getting 'finalised' - see my earlier post.

  2. #22
    DarrylBurke's Avatar
    DarrylBurke is offline Forum Police
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,252
    Rep Power
    19

    Default Re: JScrollPane not finalizing

    From your first post:
    Using JDK 6 under Netbeans IDE 7.0.1.
    Do you get identical results when testing from the command line? the NetBeans 'console' aka Output Window is a Swing component (all of the NetBeans UI is built in Swing).

    About the book you quoted, it doesn't seem too authentic. For example (emphasis added)
    if overridding finalize() it is good programming practice to use a try-catch-finally statement and to always call super.finalize() (JPL pg 47-48). This is a saftey measure to ensure you do not inadvertently miss closing a resource used by the objects calling class
    The super class can't be construed to be the 'objects calling class' no matter what the author intended that latter to mean.

    And in the code example, super.finalze() isn't invoked.

    Now, to repeat my post #14:
    Why the vagueness? either the application crashes with an OOME or it doesn't.

    If this is just about monitoring memory usage with Windows Task Manager or some other utility and observing an increasing trend, but the application never actually experiences OOME, I'd say it's not much worth bothering about -- and if considered important to the client, could probably be addressed with command line flags for gc tweaks.
    Is the application running into OOME or not?

    db
    If you're forever cleaning cobwebs, it's time to get rid of the spiders.

  3. #23
    RocketRod9 is offline Member
    Join Date
    Feb 2012
    Posts
    11
    Rep Power
    0

    Default Re: JScrollPane not finalizing

    It runs into OOME when I include JScrollPane.
    The code below runs OOME very quickly and never calls the 'finalise' method in JFrame.
    If I remove the JScrollPane and add the JTable directly to the frame, it never runs OOME and calls the finalise method of JFrame continuously.
    Java Code:
    import java.util.Vector;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    
    /*
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     */
    
    /**
     *
     * @author rodney
     * 
     * To investigate why a JScrollPane added to a JFrame prevents destruction of the JFrame and JScrollBar objects
     */
    public class MemoryLeakTest {
        static int ct;
    
        /**
         * @param args the command line arguments
         */
        public static void main(String[] args) {
          
            // repeatedly create a frame and dispose of it
            while(true)
            {
                ++ct;
                // create a JTable for stressing program
                Vector data=new Vector(), hdgs=new Vector();
                JTable table;
                JFrame fr;
                JScrollPane jsp;
    
                for(int ct=0;ct<2000;++ct)
                {
                    Vector line=new Vector();
    
                    for(int col=0;col<100;++col)
                    {
                        line.add("Row "+ct+" Col "+col);
                    }
                    data.add(line);
                }
                for(int col=0;col<100;++col)
                {
                    hdgs.add("Column "+col);
                }
                table=new JTable(data,hdgs);
                // Create the frame and add scrollpane
                fr=new JFrame("Frame #"+ct)
                {
                    protected void finalize() throws Throwable
                    {
                        try
                        {
                            System.out.println("finalizing "+this.getTitle());
                        }
                        catch(Exception e)
                        {}
                        finally
                        {
                            super.finalize();
                        }
                    }
                };
                jsp=new JScrollPane(table);
                fr.setBounds(0,0,300,200);
                fr.getContentPane().add(jsp);
                //fr.getContentPane().add(table);
                fr.setVisible(true);
                jsp=null;
                fr.dispose();
                fr=null;
                table=null;
                data=null;
            }
        }
    }
    Last edited by DarrylBurke; 02-17-2012 at 03:28 AM. Reason: Code tags

  4. #24
    DarrylBurke's Avatar
    DarrylBurke is offline Forum Police
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,252
    Rep Power
    19

    Default Re: JScrollPane not finalizing

    I ran your code without any changes and here's the end of the sysout (before I interrupted the run), copied from NetBeans
    Java Code:
    finalizing Frame #1540
    finalizing Frame #1542
    finalizing Frame #1541
    finalizing Frame #1539
    finalizing Frame #1538
    BUILD STOPPED (total time: 3 minutes 49 seconds
    One thing wrong with that code is that Swing components should always be constructed and their methods called on the EDT -- not the main thread. Even most of the methods documented as 'thread-safe' are in fact not, and that has been reflected by not documenting them as thread-safe in the Java 7 API.

    It's entirely possible that this is the same issue I described in #20, and that you get the OOME while I get finalizing may just be evidence that my machine is faster than yours. (I'm running on a quad core Q9400 @ 2.66 GHz / 2.96 GB RAM [of 4 GB installed] -- what's your system?)

    Oh, and there's no point nullling a variable that's about to go out of scope. Your code runs the same with those lines commented.

    Finally, please go through the forum FAQ and find the section about code tags. I'm adding them for you this time.

    db

    -- BB Code List - Java Programming Forum
    If you're forever cleaning cobwebs, it's time to get rid of the spiders.

  5. #25
    RocketRod9 is offline Member
    Join Date
    Feb 2012
    Posts
    11
    Rep Power
    0

    Default Re: JScrollPane not finalizing

    Further to my last post, if you replace the JScrollPane with ScrollPane, the program doesn't OOME and calls 'finalise' repeatedly.
    This illustrates my original post's findings that the problems in JScrollPane.

  6. #26
    RocketRod9 is offline Member
    Join Date
    Feb 2012
    Posts
    11
    Rep Power
    0

    Default Re: JScrollPane not finalizing

    Sorry Guys, the problem is a Mac OS X implementation of Java.
    Just ran the Memory Test program on a Windows 7 machine, and the program does call the finalise method of JFrame and consequently does not OOME.

    Maybe I should visit an equivalent Mac Java Forum OR are these issues relevant here as well??

  7. #27
    DarrylBurke's Avatar
    DarrylBurke is offline Forum Police
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,252
    Rep Power
    19

    Default Re: JScrollPane not finalizing

    If you're forever cleaning cobwebs, it's time to get rid of the spiders.

  8. #28
    doWhile is offline Moderator
    Join Date
    Jul 2010
    Location
    California
    Posts
    1,642
    Rep Power
    7

    Default Re: JScrollPane not finalizing

    Quote Originally Posted by RocketRod9 View Post
    Sorry Guys, the problem is a Mac OS X implementation of Java.
    Just ran the Memory Test program on a Windows 7 machine, and the program does call the finalise method of JFrame and consequently does not OOME.

    Maybe I should visit an equivalent Mac Java Forum OR are these issues relevant here as well??
    Thank you for the SSCCE, which reproduces the problem on my mac, which you may have to work around. Relative to the SSCCE you provided, remove the JViewport from the JScrollPane, and remove the JScrollPane from the JFrame (in other words, remove all references that point to the JScrollPane, and remove all references that the JScrollPane points to). The JScrollPane may not be garbage collected, but the data it holds should. To modify your SSCCE:


    Code Removed: see code in post below

    The above allows the JFrame to be garbage collected as well as the JTable (and data within). Its a hack that overcomes the garbage collection problem of the JScrollPane you demonstrated
    Last edited by doWhile; 02-17-2012 at 03:53 PM.

  9. #29
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,016
    Rep Power
    20

    Default Re: JScrollPane not finalizing

    Quote Originally Posted by RocketRod9 View Post
    According to JavaDocs, all Classes derive from java.lang.Object, and since java.lang.Object has a finalize method ALL Classes have an inherited finalise method.
    Quoting from here, which is in the resources at the bottom of this Oracle GC article explaining how GC works.
    "
    The following steps describe the lifetime of a finalizable object obj—that is, an object whose class has a non-trivial finalizer (see Figure 1):

    1.When obj is allocated, the JVM internally records that obj is finalizable (this typically slows down the otherwise fast allocation path that modern JVMs have).

    2.When the garbage collector determines that obj is unreachable, it notices that obj is finalizable (as it had been recorded upon allocation) and adds it to the JVM's finalization queue. It also ensures that all objects reachable from obj are retained, even if they are otherwise unreachable, as they might be accessed by the finalizer. Figure 2 illustrates this for an instance of Image1.

    3.At some point later, the JVM's finalizer thread will dequeue obj, call its finalize() method, and record that obj's finalizer has been called. At this point, obj is considered to be finalized.

    4.When the garbage collector rediscovers that obj is unreachable, it will reclaim its space along with everything reachable from it (provided that the latter is otherwise unreachable).
    "

    "Non-trivial" means "not the Object finalize()".

    By adding a finalize() into your "test" you have changed how the gc works. Indeed, similar to the situation Darryl mentioned earlier about repaint, a busy thread that creates lots of short lived objects that have a finalize() can result in the finalize queue building up as the finalizer is generally low priority. This can easily result in an OOME. Which is what I suspect you are seeing in your test...either that or it is a version of Darryl's repaint queue problem.

    As I have said a couple of times on this thread, finalize() is not a suitable method of determining garbage collection. Take heap dumps (usually several) and track object retention, and where that is occurring.

    So, on a Mac without the finalize() method does this throw an OOME?
    In addition, on a Mac with the Swing objects constructed in the EDT (as they should be) does it throw an OOME?

    Until those two things have been checked (ie the test code has been corrected to remove the problems it currently contains) it is not a valid test.
    DarrylBurke and Fubarable like this.

  10. #30
    doWhile is offline Moderator
    Join Date
    Jul 2010
    Location
    California
    Posts
    1,642
    Rep Power
    7

    Default Re: JScrollPane not finalizing

    Quote Originally Posted by Tolls View Post
    So, on a Mac without the finalize() method does this throw an OOME?
    In addition, on a Mac with the Swing objects constructed in the EDT (as they should be) does it throw an OOME?

    Until those two things have been checked (ie the test code has been corrected to remove the problems it currently contains) it is not a valid test.
    On my system (Mac OS X (10.6), JRE 6), the answer is yes and yes. After testing the code provided, an OOME is thrown under the many conditions I tested (no finalize, run on the EDT using SwingUtilities, and combinations of modifications).

    A workaround built off of the code the original poster provided is to manually release the references pointing out of the JScrollPane (and into as well for good measure). The code the original poster posted does throw an OOME (and does with SwingUtilities added and finalize removed as well), the code below does NOT throw an OOME (with the setViewportView(null) line removed it does throw an OOME):

    Java Code:
     public static void main(String[] args) throws Exception{
           
        	// repeatedly create a frame and dispose of it
        	while(true)
        	{
        		SwingUtilities.invokeAndWait(new Runnable(){
        			public void run(){
        				System.out.println(ct);
        				++ct;
        				// create a JTable for stressing program
        				Vector data=new Vector(), hdgs=new Vector();
        				JTable table;
        				final JFrame fr;
        				
    
        				for(int ct=0;ct<2000;++ct)
        				{
        					Vector line=new Vector();
    
        					for(int col=0;col<100;++col)
        					{
        						line.add("Row "+ct+" Col "+col);
        					}
        					data.add(line);
        				}
        				for(int col=0;col<100;++col)
        				{
        					hdgs.add("Column "+col);
        				}
        				table=new JTable(data,hdgs);
        				final JScrollPane jsp=new JScrollPane(table);
    
        				// Create the frame and add scrollpane
        				fr=new JFrame("Frame #"+ct)
        				{
        					/**
        					* Override dispose to manually release references of the contained JScrollPane
        					*/
        					@Override
        					public void dispose(){
        						//remove the references to the JScrollPane - not directly necessary to overcome OOME
        						jsp.getParent().removeAll();
        						//removes the references from the JScrollPane,
        						//comment out the following line and an OOME is thrown on Mac
        						jsp.setViewportView(null);
        						super.dispose();
        					}
        				};
        				fr.setBounds(0,0,300,200);
        				fr.getContentPane().add(new JPanel().add(jsp));
        				fr.setVisible(true);
        				fr.dispose();
        			}
        		});
            }
        }
    Last edited by doWhile; 02-17-2012 at 04:09 PM.
    Fubarable likes this.

  11. #31
    RocketRod9 is offline Member
    Join Date
    Feb 2012
    Posts
    11
    Rep Power
    0

    Default Re: JScrollPane not finalizing

    Bingo 'doWhile'- you found it.
    Thank you for your time and patience. It is much appreciated.

    Thank you all who provided positive and helpful feedback for my problem.

    I can now move forward with a workaround.

Page 2 of 2 FirstFirst 12

Similar Threads

  1. JScrollPane - A little help please
    By Ermm in forum New To Java
    Replies: 7
    Last Post: 01-23-2012, 06:26 AM
  2. JScrollPane
    By mitra in forum AWT / Swing
    Replies: 2
    Last Post: 11-15-2011, 03:20 PM
  3. Help with jScrollPane
    By weikang in forum SWT / JFace
    Replies: 1
    Last Post: 02-04-2011, 03:30 AM
  4. JScrollPane
    By hiddenpremise in forum AWT / Swing
    Replies: 2
    Last Post: 12-25-2010, 05:15 AM
  5. jscrollpane
    By kaemonsaionji in forum New To Java
    Replies: 3
    Last Post: 02-25-2009, 08:39 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •