CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 7 of 7
  1. #1
    Join Date
    Jun 2008
    Posts
    61

    [RESOLVED] how to disconnect to database in this case?

    I'm working with JDBC.

    1) I want to disconnect to database in a destructor because my class uses the connection during execution time. Please give me a hand where I should put my disconnectToDatabase() method.

    2) I googled for that and I used finalize() method but when I closed my frame, it didn't show the message dialog. I think there is memory leak.
    So in fact, when is finalize() method invoked? How to disconnect to database in this case?


    Code:
    public class LeftPane extends JPanel
    {
            private DatabaseLoader databaseLoader;
    	
            public LeftPane()
            {
                    try {
    			databaseLoader = new DatabaseLoader();			
    		} catch (ClassNotFoundException e) {
    			System.err.println("Have no a driver");
    		}
    
                    ...
    
                    // connect to database
    		try {
    			databaseLoader.connectToDatabase();		
    			...
    		} catch (SQLException e) {
    			System.err.println("Database error");
    		}
                    ...
             }
    
             protected void finalize() throws Throwable 
    	{		
    		JOptionPane.showMessageDialog(null, "End"); // it doesn't show when I close my app.
    
                    // disconnect to database
    		databaseLoader.disconnectToDatabase();
    		super.finalize();
    	};
    }
    Thank you.
    Last edited by Emerald214; November 21st, 2009 at 04:04 AM.

  2. #2
    Join Date
    May 2002
    Location
    Lindenhurst, NY
    Posts
    867

    Re: how to disconnect to database in this case?

    I made the same exact mistake when I first started as a full-time Java developer 3 years ago. I had come from C++ & was also looking for the Java equivalent of a destructor, also to close a database connection. I found finalize. Then I was told that I can't count on finalize. In Java, you can't count on when your objects will be destroyed by the garbage collector. So basically, there's no destructors in java (there is finalize, but I never use it & don't know of any practical uses of it).

    I think you should look at an object constructor as just something to get the objects variables initialized, but not for things like opening & closing file & database connections. Instead add 'initialize() / end()' methods (or whatever you want to name them) & explicitly call them. That's where I open & close database connections.

  3. #3
    Join Date
    May 2002
    Location
    Lindenhurst, NY
    Posts
    867

    Re: how to disconnect to database in this case?

    Quote Originally Posted by Emerald214 View Post
    So in fact, when is finalize() method invoked?
    I'm pretty sure its when the object is garbage collected. And you can't predict when the garbage collector will decide to do it.

  4. #4
    Join Date
    Jun 2008
    Posts
    61

    Re: how to disconnect to database in this case?

    I'm sorry, I read your reply many times but I still don't understand, so exactly where I should put my disconnectToDatabase()?
    I can't put it at the end of my constructor because my class which extends from DefaultTreeRenderer uses that connection during execution time (when I traverse my database tree).
    As you say, my disconnectToDatabase() is your end() method, but I don't know where to explicitly call it. I think it just could be put in somewhere when my frame is closed.

  5. #5
    Join Date
    Apr 2007
    Posts
    425

    Re: how to disconnect to database in this case?

    Unless you have a good reason to do so, you generally should only leave a session open for when you require it. think of it as something like this:


    Code:
    public void doDatabaseStuff(Object ... args) {
    
    // 1. obtain a connection to the database
    // 2. Read / Update some fields
    // 3. Close connection
    
    // 4. Do some other processing
    // 5. Yet again, do some other processing that still no longer requires the database
    // 6. ....
    
    }
    Not sure if you are passing a singleton object around with an open connection to the database or not?
    ------
    If you are satisfied with the responses, add to the user's rep!

  6. #6
    dlorde is offline Elite Member Power Poster
    Join Date
    Aug 1999
    Location
    UK
    Posts
    10,163

    Re: how to disconnect to database in this case?

    Martin O is right, sadly there are no destructors in Java, and the finalize isn't suitable because there's no guarantee when, or even if, it will be called.

    The usual way of closing I/O resources in Java is in a 'finally' block. The path of execution will always pass through the finally block before leaving the method, even if an exception is thrown.

    The usual structure is something like this:
    Code:
    // declare resource handle(s)
    Resource resource = null;
    
    try {
       resource = acquireResource();
       
       ... // use the resource
       ...
    
    }
    catch (FooException ex) {
    
       ... // handle exception(s)
       ...
    }
    finally {  // will always be executed before returning
    
       // clean up
       if (resource != null) {
          resource.close();
       }
       ...
    }
    In practice, some resources can throw exceptions from their close methods, so you may see a finally block containing a nested try..catch (ugly):
    Code:
    finally {
       if (resource != null) {   
          try {
             resource.close();
          }
          catch(ResourceException re) {
             // log error
          }
       }
    }
    Exception handling in Java is a great feature (although it could, arguably, be better), but the the lack of deterministic destructors is a real pain. I've never heard a convincing explanation why they couldn't be implemented (relatively) independently of garbage collection. Judicious use of utility methods can make this stuff look less ugly, but at the end of the day, we're stuck with it.

    There was an interesting proposal for Java 7 to enhance the 'try' declaration to automatically close all 'closeable' resources acquired inside the block, but it was rejected for some reason.

    The most likely way for the world to be destroyed, most experts agree, is by accident. That's where we come in; we're computer professionals. We cause accidents...
    N. Borenstein
    Last edited by dlorde; November 21st, 2009 at 01:50 PM.
    Please use [CODE]...your code here...[/CODE] tags when posting code. If you get an error, please post the full error message and stack trace, if present.

  7. #7
    Join Date
    Jun 2008
    Posts
    61

    Re: how to disconnect to database in this case?

    It's clear. I got it. It's a grade-A explanation. Thank everybody for your helps.

Posting Permissions

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





Click Here to Expand Forum to Full Width

Featured