?
Solved

How to kill idle connection after some time in JDBC?

Posted on 2003-03-03
9
Medium Priority
?
504 Views
Last Modified: 2010-08-05
I want to develop a JDBC application software to connect client to database for database query. Users may keep the connection open but do not do anything, after the connection is idle(no activity from the user) for 1 hour(for example), How can I use JDBC to keep track of idle time and disconnect the user from database ?

 Thanks a lot.
0
Comment
Question by:xxdxxd
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
9 Comments
 
LVL 35

Accepted Solution

by:
girionis earned 200 total points
ID: 8057710
 There is no need to do it. Opening/closing conenctions to the database requires mroe resources than actually conserving these connections and reuse them when necessary. If you want to implement a smart connection pooling solution take a look here:

http://www.webdevelopersjournal.com/columns/connection_pool.html
0
 

Author Comment

by:xxdxxd
ID: 8057911

  I think my question is not the same as connection pooling problem. Basically, I do not want to allow the users to keep the connection while  they go for lunch or forget to close the connection when their tasks are done. If the connection is idle for some time, the java application will force the connection to close.
 
  How can I do that?
0
 

Expert Comment

by:GumB
ID: 8058290
I think you are missing the point of girionis suggestion.  If you use a pool, your clients won't be getting a connection and hanging on to it for any period of time at all.  When they press a button, for example, they momentarily grab a connection from the pool which is given back to the pool as soon as the query or update or whatever finishes executing ...no one hangs on to a connection for any length of time at all.

The issue here is a design one ...you are giving each client thier own connection, which they hang on to until they logout or otherwise disappear.  With a pool, your connections are grabbed from the pool, used for a single (or possibly a couple) of statements ...then returned to the pool.  Do you see the difference?

ie. (where adminPool is the connection pool object)

public String doStuff() {

  StringBuffer tables = new StringBuffer();
  try {
    // Grab a connection from the pool...
    Connection connection = adminPool.getConnection();
    // Use it...
    DBResults results = DatabaseUtilities.getQueryResults(
      connection, createQueryString(2), false
    );
    // Release the connection back to the pool...
    adminPool.free(connection);
    tables.append(results.toHTMLTable("dark","off"));
  } catch(Exception e) {
    tables.append("Error: ").append(e.toString());
  }
  return tables.toString();
}
0
Get 15 Days FREE Full-Featured Trial

Benefit from a mission critical IT monitoring with Monitis Premium or get it FREE for your entry level monitoring needs.
-Over 200,000 users
-More than 300,000 websites monitored
-Used in 197 countries
-Recommended by 98% of users

 
LVL 14

Expert Comment

by:Tommy Braas
ID: 8059805
Ok, to help you solve the problem immediately at hand, maybe the following will help:

import java.util.*;

class CustomObservable extends Observable
{
   public update()
   {
      setChanged();
      notifyObservers();
   }
}

public class TimeOutThread extends Thread
{
   CustomObservable observers;

   long timeOutInMillis;
   long sleepInterval = 1000;
   long counter = 0;

   boolean stopped = false;

   public TimeOutThread()
   {
      observers = new CustomObservable();
   }

   public TimeOutThread(Observer anObserver)
   {
      this();
      addObserver(anObserver);
   }

   public void addObserver(Observer anObserver)
   {
      observers.addObserver(anObserver);
   }

   public void deleteObserver(Observer anObserver)
   {
      observers.deleteObserver(anObserver);
   }

   public void run()
   {
      while( !stopped )
      {
         try
         {
            Thread.sleep(sleepInterval);
            counter += sleepInterval;
            if( counter >= timeOutInMillis )
            {
               observers.update();
            }
         }
         catch(InterruptedException ie)
         {
            counter = 0;
         }
      }
   }
 

   public void setSleepInterval(long sleepIntervalInMillis)
   {
      this.sleepInterval = sleepIntervalInMillis;
   }

   public void setSleepInterval(long sleepIntervalInMillis)
   {
      this.sleepInterval = sleepIntervalInMillis;
   }

   public void reset()
   {
      try
      {
         Thread.sleep(sleepInterval/4);
         interrupt();
      }
      catch(InterruptedException ie)
      {
      }
   }

   public void stop()
   {
      stopped = true;
   }
}

You need to implement the 'Observer' interface in the class you would want to observe the TimeOutThread. The 'Observer' interface declares one method, 'update', which will be called by the timer thread when the time out occurs.
0
 
LVL 1

Assisted Solution

by:tutran
tutran earned 200 total points
ID: 8066304
If you application is a web application, you may want to have a UserProfile that has a "conn" as a member variable and implement
javax.servlet.http.HttpSessionBindingListener and specify two methods.  This way, when session is invalidated, the connection will be closed by web container.  If your app is not a web app, then you want to bootstrap conn.close() somewhere similar:

public void valueBound(HttpSessionBindingEvent e) {
}

public void valueUnbound(HttpSessionBindingEvent ev) {
    try {
       conn.close()
    } catch (Exception e) {
    }
}

0
 

Expert Comment

by:CleanupPing
ID: 9058960
xxdxxd:
This old question needs to be finalized -- accept an answer, split points, or get a refund.  For information on your options, please click here-> http:/help/closing.jsp#1 
EXPERTS:
Post your closing recommendations!  No comment means you don't care.
0
 
LVL 35

Expert Comment

by:TimYates
ID: 9721271
No comment has been added lately, so it's time to clean up this TA.
I will leave a recommendation in the Cleanup topic area that this question is:

Split between girionis and tutran.

Please leave any comments here within the next seven days.

PLEASE DO NOT ACCEPT THIS COMMENT AS AN ANSWER!

TimYates
EE Cleanup Volunteer
0
 
LVL 35

Expert Comment

by:girionis
ID: 9721305
 FIne by me :)
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction This article is the last of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers our test design approach and then goes through a simple test case example, how …
In this post we will learn different types of Android Layout and some basics of an Android App.
Viewers learn about the third conditional statement “else if” and use it in an example program. Then additional information about conditional statements is provided, covering the topic thoroughly. Viewers learn about the third conditional statement …
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…
Suggested Courses
Course of the Month13 days, 17 hours left to enroll

800 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question