Threading with connection pool
Hi
My application is an interface to ldap directory. I have not used any ldap open source api to retrieve data from ldap. I have written connection pool that will help the application to connect to the ldap. It's working fine, but it's creating threads which are not invited.
ConnectionPool class takes care of the connection storage and creation, while Housekeeping thread relases these connection when idle after a given time.
Can someone please help in finding the problem in the code that creates additional threads.
package com.ba.cdLookup.manager;
import com.ba.cdLookup.exception.CDLookupException;
import com.ba.cdLookup.server.CdLookupProperties;
import java.util.Vector;
import javax.naming.Context;
import javax.naming.NamingException;
public class HouseKeeperThread extends Thread {
* Apache Logger to log erro/info/debug statements.
protected static org.apache.commons.logging.Log log = org.apache.axis.components.logger.LogFactory
.getLog(HouseKeeperThread.class.getName());
private static HouseKeeperThread houseKeeperThread;
* Close all connections existing.
* @param connections
* void
private void closeConnections(Vector connections) {
String methodIdentifier = "closeConnections";
int numOfConn = connections.size();
try {
for (int i = 0; i < numOfConn; i++) {
Context context = (Context) connections.get(i);
if (context != null) {
context.close();
context = null;
connections.remove(i);
numOfConn--;
log.info(" connection name:" + context
+ " removed. Threadcount =" + (connections.size()));
} catch (NamingException e) {
String errMsg = "CDLdapBuilder connect() - failure while releasing connection "
+ " Exception is " + e.toString();
log.error(errMsg);
} catch (Exception e) {
String errMsg = "CDLdapBuilder connect() - failure while releasing connection "
+ " Exception is " + e.toString();
log.error(errMsg);
* Thread run method
public void run() {
String methodIdentifier = "run";
try {
while(true){
log.debug("house keeping :" + this + " ---sleep");
//sleep(100000);
log.debug("house keeping :" + this + " startd after sleep");
sleep(CdLookupProperties.getHouseKeepConnectionTime());
ConnectionPool connectionPool = ConnectionPool
.getConnectionPool();
Vector connList = connectionPool.getAvailableConnections();
closeConnections(connList);
} catch (CDLookupException cde) {
log.error(methodIdentifier + " " + cde.getStackTrace());
} catch (InterruptedException ie) {
log.error(methodIdentifier + " " + ie.getStackTrace());
* @param connectionPool
* @return
* Thread
public static Thread getInstance() {
if(houseKeeperThread==null){
houseKeeperThread = new HouseKeeperThread();
return houseKeeperThread ;
package com.ba.cdLookup.manager;
import com.ba.cdLookup.exception.CDLookupException;
import com.ba.cdLookup.server.CdLookupProperties;
import com.ba.cdwebservice.schema.cdLookupPacket.LookupFailureReasons;
import java.util.Properties;
import java.util.Vector;
import javax.naming.Context;
import javax.naming.NamingException;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
* ConnectionPool class manages, allocates LDAP connections. It works as a lazy
* binder and retrieves connections only when required. It doesn't allow
* connection greater then the maximum connection stated.
* To retrieve a connection the singelton method getConnectionPool is to used,
* which retruns thread safe singleton object for the connection.
public class ConnectionPool implements Runnable {
private int initialConnections = 0;
private int maxConnections = 0;
private boolean waitIfBusy = false;
private Vector availableConnections, busyConnections;
private boolean connectionPending = false;
private static int threadCount = 0;
* classIdentifier
private final String classIdentifier = "ConnectionPool";
* Apache Logger to log erro/info/debug statements.
protected static org.apache.commons.logging.Log log = org.apache.axis.components.logger.LogFactory
.getLog(CDLdapBuilder.class.getName());
* To get the attribute a systemaccessfor out of the search result
private String vendorContextFactoryClass = "com.sun.jndi.ldap.LdapCtxFactory";// "com.ibm.jndi.LDAPCtxFactory";
* context factory to use
private String ldapServerUrl = "LDAP://test.ldap.com"; // default ldap
* server live used by default
private String searchBase;
* environment properties.
private Properties env;
* DirContext
private javax.naming.directory.DirContext ctx;
* default search base to be used in Corporate Directory searches
private String defaultSearchBase = "dc=Pathway";
* search criteria
private String searchAttributes;
* search filter to retrieve data from CD
private String searchFilter;
* CorporateDirectoryLookup Constructor
* <p>
* loads the setup parameters from the properties file and stores them
* Makes a connection to the directory and sets default search base
* @throws CDLookupException
* @throws CDLookupException
private ConnectionPool() throws CDLookupException {
this.maxConnections = CdLookupProperties.getMaxConnection();// maxConnections;
this.initialConnections = CdLookupProperties.getInitialConnection();
this.waitIfBusy = CdLookupProperties.isWaitIfBusy();
this.searchBase = CdLookupProperties.getDefaultSearchBase();
//for local env testing
// this.maxConnections = 5;
// this.initialConnections = 1;
// this.waitIfBusy = true;
* For keeping no of connections in the connection pool if
* (initialConnections > maxConnections) { initialConnections =
* maxConnections; }
availableConnections = new Vector(maxConnections);
busyConnections = new Vector(maxConnections);
for (int i = 0; i < maxConnections; i++) {
availableConnections.add(makeNewConnection());
* ConnectionPoolHolder provide Thread safe singleton
* instance of ConnectionPool class
private static class ConnectionPoolHolder {
* connection pool instance
private static ConnectionPool connectionPool = null;
* If no ConnectionPool object is present, it creates instance of
* ConnectionPool class and initiates thread on that.
* @return ConnectionPool Returns singleton object of ConnectionPool
* class.
* @throws CDLookupException
private static ConnectionPool getInstance() throws CDLookupException {
if (connectionPool == null) {
connectionPool = new ConnectionPool();
new Thread(connectionPool).start();
// Initiate house keeping thread.
HouseKeeperThread.getInstance().start();
return connectionPool;
* Returns singleton object of ConnectionPool class.
* @return ConnectionPool
* @throws CDLookupException
public static ConnectionPool getConnectionPool() throws CDLookupException {
return ConnectionPoolHolder.getInstance();
* getConnection retrieves connections to the corp directory. In case
* there is no available connections in the pool then it'll try to
* create one, if the max connection limit for the connection pool
* reaches then this waits to retrieve one.
* @return Context
* @throws CDLookupException
public synchronized Context getConnection() throws CDLookupException {
String methodIdentifier = "getConnection";
if (!availableConnections.isEmpty()) {
int connectionSize = availableConnections.size() - 1;
DirContext existingConnection = (DirContext) availableConnections
.get(connectionSize);
availableConnections.remove(connectionSize);
* If connection on available list is closed (e.g., it timed
* out), then remove it from available list and repeat the
* process of obtaining a connection. Also wake up threads that
* were waiting for a connection because maxConnection limit was
* reached.
if (existingConnection == null) {
notifyAll(); // Freed up a spot for anybody waiting
return (getConnection());
} else {
busyConnections.add(existingConnection);
return (existingConnection);
} else {
* Three possible cases: 1) You haven't reached maxConnections
* limit. So establish one in the background if there isn't
* already one pending, then wait for the next available
* connection (whether or not it was the newly established one).
* 2) You reached maxConnections limit and waitIfBusy flag is
* false. Throw SQLException in such a case. 3) You reached
* maxConnections limit and waitIfBusy flag is true. Then do the
* same thing as in second part of step 1: wait for next
* available connection.
if ((totalConnections() < maxConnections) && !connectionPending) {
makeBackgroundConnection();
} else if (!waitIfBusy) {
throw new CDLookupException("Connection limit reached", 0);
* Wait for either a new connection to be established (if you
* called makeBackgroundConnection) or for an existing
* connection to be freed up.
try {
wait();
} catch (InterruptedException ie) {
String errMsg = "Exception raised =" + ie.getStackTrace();
log.error(errMsg);
throw new CDLookupException(classIdentifier, methodIdentifier,
errMsg, ie);
// connection freed up, so try again.
return (getConnection());
* You can't just make a new connection in the foreground when none are
* available, since this can take several seconds with a slow network
* connection. Instead, start a thread that establishes a new
* connection, then wait. You get woken up either when the new
* connection is established or if someone finishes with an existing
* connection.
private void makeBackgroundConnection() {
connectionPending = true;
try {
Thread connectThread = new Thread(this);
log.debug("background thread created");
connectThread.start();
} catch (OutOfMemoryError oome) {
log.error("makeBackgroundConnection ="+ oome.getStackTrace());
* Thread run method
public void run() {
String methodIdentifier = "run";
try {
Context connection = makeNewConnection();
synchronized (this) {
availableConnections.add(connection);
connectionPending = false;
notifyAll();
} catch (Exception e) { // SQLException or OutOfMemory
// Give up on new connection and wait for existing one
// to free up.
String errMsg = "Exception raised =" + e.getStackTrace();
log.error(errMsg);
* This explicitly makes a new connection. Called in the foreground when
* initializing the ConnectionPool, and called in the background when
* running.
* @return Context
* @throws CDLookupException
private Context makeNewConnection() throws CDLookupException {
String methodIdentifier = "makeNewConnection";
Context context = null;
env = new Properties();
log.debug("inside " + methodIdentifier);
try {
env.put(Context.INITIAL_CONTEXT_FACTORY,
getVendorContextFactoryClass());
env.put(Context.PROVIDER_URL, getLdapServerUrl());
env.put("com.sun.jndi.ldap.connect.pool", "true");
context = new InitialDirContext(env);
} catch (NamingException e) {
String errMsg = "CDLdapBuilder connect() - failure while attempting to contact "
+ ldapServerUrl + " Exception is " + e.toString();
throw new CDLookupException(classIdentifier, methodIdentifier,
errMsg, e, LookupFailureReasons.serviceUnavailable);
} catch (Exception e) {
String errMsg = "CDLdapBuilder connect() - failure while attempting to contact "
+ ldapServerUrl + " Exception is " + e.toString();
throw new CDLookupException(classIdentifier, methodIdentifier,
errMsg, e, LookupFailureReasons.serviceUnavailable);
log.info("new connection :" + (threadCount++) + " name =" + context);
log.debug("exit " + methodIdentifier);
return context;
* releases connection to the free pool
* @param context
public synchronized void free(Context context) {
busyConnections.remove(context);
availableConnections.add(context);
// Wake up threads that are waiting for a connection
notifyAll();
* @return int give total no of avail connections.
public synchronized int totalConnections() {
return (availableConnections.size() + busyConnections.size());
* Close all the connections. Use with caution: be sure no connections
* are in use before calling. Note that you are not <I>required</I> to
* call this when done with a ConnectionPool, since connections are
* guaranteed to be closed when garbage collected. But this method gives
* more control regarding when the connections are closed.
public synchronized void closeAllConnections() {
closeConnections(availableConnections);
availableConnections = new Vector();
closeConnections(busyConnections);
busyConnections = new Vector();
* Close all connections existing.
* @param connections
* void
private void closeConnections(Vector connections) {
String methodIdentifier = "closeConnections";
try {
for (int i = 0; i < connections.size(); i++) {
Context context = (Context) connections.get(i);
if (context != null) {
log.info(" connection name:" + context
+ " removed. Threadcount =" + (threadCount++));
context.close();
context = null;
} catch (NamingException e) {
String errMsg = "CDLdapBuilder connect() - failure while attempting to contact "
+ ldapServerUrl + " Exception is " + e.toString();
log.error(errMsg);
public synchronized String toString() {
String info = "ConnectionPool(" + getLdapServerUrl() + ","
+ getVendorContextFactoryClass() + ")" + ", available="
+ availableConnections.size() + ", busy="
+ busyConnections.size() + ", max=" + maxConnections;
return (info);
* @return the defaultSearchBase
public final String getDefaultSearchBase() {
return defaultSearchBase;
* @param defaultSearchBase
* the defaultSearchBase to set
public final void setDefaultSearchBase(String defaultSearchBase) {
this.defaultSearchBase = defaultSearchBase;
* @return the ldapServerUrl
public final String getLdapServerUrl() {
return ldapServerUrl;
* @param ldapServerUrl
* the ldapServerUrl to set
public final void setLdapServerUrl(String ldapServerUrl) {
this.ldapServerUrl = ldapServerUrl;
* @return the vendorContextFactoryClass
public final String getVendorContextFactoryClass() {
return vendorContextFactoryClass;
* @param vendorContextFactoryClass
* the vendorContextFactoryClass to set
public final void setVendorContextFactoryClass(
String vendorContextFactoryClass) {
this.vendorContextFactoryClass = vendorContextFactoryClass;
* @return the availableConnections
public final Vector getAvailableConnections() {
return availableConnections;
}
hi ejp
Thx for the reply.
// Enable connection pooling
env.put("com.sun.jndi.ldap.connect.pool", "true");
Is this suffice to get the connection pool working,
Should i merely have a thread to maintain the connection with the ldap that uses sun's connection pool; or allow requestes to create new object for the connection and still this pool will hold.
for example in the above code instead to housekeep the thread merely maintain connection with the pool
or
should I directly connect each object with the ldap?
I am unable to understand how exactly sun's connection pool is working and how it should be used. I have gone thru the following example but picture is still hazy and undigestable to me.
java.sun.com/products/jndi/tutorial/ldap/connect/pool.html
Rgds
Similar Messages
-
What is the usual way of accessing Oracle by JSF with connection pooling?
I am writing to access Oracle by JSF with connection pooling.
EJB is too difficult for me.
What is the simple way of doing it?
thanksLeung,
I believe there should be some sample code available via the JavaServer Pages Samples Web page.
Good Luck,
Avi. -
Stored Procedure Call with Connection Pools
Hi everybody,
I have changed my Database-Connection to Connection Pooling.
No I try to call a stored procedure like this:
Connection connection;
CallableStatement callStmt;
Integer sp_result;
//--- Set callable stored procedure
String call = "{?=call myStoredProcedure(?,?,?)}";
try {
if( connection != null ) {
callStmt = connection.prepareCall( call );
callStmt.registerOutParameter( 1, java.sql.Types.INTEGER );
callStmt.setInt( 2, 3 );
callStmt.setString( 3, plz );
callStmt.setString( 4, ort );
callStmt.execute( call );
sp_result = new Integer( callStmt.getInt(1) );
callStmt.close();
result = sp_result.intValue();
} else {
log.error( "Connection = null" );
} catch( SQLException ex ) {
log.error( ex.toString() );
ServletUtils.forwardRequest(this, request, response,
"/error.jsp", "errorMsg", ex.toString() );
Without Connection Pooling, my Connection is of
'weblogic.jdbc.mssqlserver4.MicrosoftConnection'
With Connection Pooling my Connection is of
'weblogic.jdbc2.rmi.SerialConnection'
And now, the stored procedure can't be found anymore.
There comes an SQLException:
Gespeicherte Prozedur 'myStoredProcedure' konnte nicht gefunden werden.
Severity 16, State 62, Procedure 'myDBServer null', Line 5
One possibility is that the SerialConnection can't call the stored procedure
like the Microsoft-specific Connection (I use MS-SQL-Server)
Another is that the call have to be another stucture.
I would be pleased if somebody is expirienced in this behaviour.
Thousand thanx,
Hammer.You need to use a DataModifyQuery as your query does not return anything.
James : http://www.eclipselink.org -
ODI 11.1.1.7.0 connect to DB with connection pool
Hello!
ODI standalone agent 11.1.1.7.0 now make a connect to DB with connection pool and set "client identifier" in the session.
How to disable connection pooling?
Thank youSolved by downloading and installing
Version 11.1.0.7.0
Instant Client Package - Basic: All files required to run OCI, OCCI, and JDBC-OCI applications
from http://www.oracle.com/technology/software/tech/oci/instantclient/htdocs/winsoft.html. -
Where can I get a db2 jdbc driver with connection pool
hi,all
I want to look for a free jdbc driver to connect to db2 using with connection pool.
it isn't present in db2java.zip
thanks and regards
[email protected]To find JDBC drivers take a look at SUN's overview at http://industry.java.sun.com/products/jdbc/drivers
-
How can i improve database connectivity with connection pool
Hi,
I used to create a connection to DB per session since the application is pretty small. Now i want to improve the db connectrion with connection pool. However, i am still confused since the book i read says that i have to change something in server.xml in the tomcat server while other people in this forum actually implement a connection pool class. Isnt it has been built into the servlet container? if yes, how can i use it? I suppose i only have to open the connection and the connection pool will reclaim the resource when the session is terminated in the same way the gabage collector reclaim resource when no reference is associated to object, am i correct?
Thaithe documentation for Tomcat 5 DB pooling can be found at:
http://jakarta.apache.org/tomcat/tom...les-howto.html
Here are the Tomcat 4 docs:
http://jakarta.apache.org/tomcat/tom...les-howto.html
The administration console can be found at (under default install):
http:localhost:8080/admin
But, you have to set up a user and password in your
<tomcat-install>/conf/tomcat-users.xml file.
You need to add an "admin" role and a user that will be assigned this
role like this (obviously you won't be using "tomcat" as your password):
<?xml version='1.0' encoding='utf-8'?>
<tomcat-users>
<role rolename="admin"/>
<user username="tomcat" password="tomcat" roles="admin"/>
</tomcat-users>
So, I can log in as Tomcat and have admin privs.
Tomcat 5
http://jakarta.apache.org/tomcat/tom...ger-howto.html
Tomcat 4
http://jakarta.apache.org/tomcat/tom...ion%20A ccess
i'm sure this helps u -
hi,
I have problems with Weblogic 5.1 connection pool. Normally it works
fine, but
under heavy load the connection pool doesn't work at all: it
negotiates a new connection every time.
Has anyone else had problems like this?
regards, EKMitesh Patel wrote:
What is your max capacity of the pool? Generally, max capacity value of
the pool should be no. of concurrent users connecting to database at
peak load.Hi Eino. Actually, I'll disagree temporarily with Mitesh ;-)
If your application is designed so that all JDBC work is done
during a single client-server invoke, such as in stateless session
beans, or servlets etc, you should only need as many connections
in the pool as your server has execute-threads. This is because
each thread will be handling one client at a time, and as long as
the code gets a pool connection, uses it, and closes it during the
one invocation, the closed connection will be there for the next.
one.
Let me see your pool definition. The only issue that may
cause occasional problems like you see, is if pool refresh is
running. Pool refresh will temporarily reserve all the currently-
unused pool conenctions to test them, and during this time, any
incoming application demand will cause the pool to make new connections
(or throw an exception!) to meet demand. If you have testConnsOnReserve
set to true, this is all the pool checking you need IMO. I would set
the refresh minute parameter to 99999999 to effectively turn off
refresh. I'm betting that will solve your issue. Let me know...
Joe
>
>
Mitesh
Eino Komsi wrote:
hi,
I have problems with Weblogic 5.1 connection pool. Normally it works
fine, but
under heavy load the connection pool doesn't work at all: it
negotiates a new connection every time.
Has anyone else had problems like this?
regards, EK -
Cursor bound to out parameter with Connection Pool
Is it possible to retrieve a cursor bound to an out parameter when using the thin
driver to establish the connection pool to the database? I am currently using
the JDriver to connect create the pool and the pool driver to connect from the
app to the connection pool. We'd like to avoid using the Oracle client if possible.
Currently I register the out parameter as java.sql.Types.OTHER, then call getResultSet(1)
on the weblogic.jdbc.pool.CallableStatement object. But it breaks when I change
the connection pool to use the thin driver. The error is at the bottom of this
post.
I think I could possibly get the current pool driver to work if can find some
documentation on these two methods:
void registerOutParameter(int i, int j, int k, int l)
void registerOutParameter(int i, int sqlType, java.lang.String typeName)
I have no idea what to put in for the ints in the first method or for sqlType
or typeName. Can anyone point me to where I can find this documentation?
E-docs mentions this class: weblogic.jdbc.vendor.oracle.OracleCallableStatement.
(http://edocs.bea.com/wls/docs61/jdbc/thirdparty.html#1023867). Should I consider
this? If so where is it?
Thanks a lot,
Matt Savino
<<< error when using thin driver >>>
preparing callable stmt
callable stmt prepared, java.sql.Types.OTHER = 1111
java.sql.SQLException: Invalid column type
at oracle.jdbc.dbaccess.DBError.throwSqlException(DBError.java:168)
at oracle.jdbc.dbaccess.DBError.throwSqlException(DBError.java:210)
at oracle.jdbc.dbaccess.DBError.throwSqlException(DBError.java:273)
at oracle.jdbc.driver.OracleStatement.get_internal_type(OracleStatement.java:4560)
at oracle.jdbc.driver.OracleCallableStatement.registerOutParameter(OracleCallableStatement.java:225)
at oracle.jdbc.driver.OracleCallableStatement.registerOutParameter(OracleCallableStatement.java:350)
at weblogic.jdbc.pool.Statement.registerOutParameter(Statement.java:617)
at jsp_servlet._reportmanager.__thin_outputresultset._jspService(__thin_outputresultset.java:145)
at weblogic.servlet.jsp.JspBase.service(JspBase.java:27)
at weblogic.servlet.internal.ServletStubImpl.invokeServlet(ServletStubImpl.java:263)
at weblogic.servlet.internal.ServletStubImpl.invokeServlet(ServletStubImpl.java:200)
at weblogic.servlet.internal.WebAppServletContext.invokeServlet(WebAppServletContext.java:2390)
at weblogic.servlet.internal.ServletRequestImpl.execute(ServletRequestImpl.java:1959)
at weblogic.kernel.ExecuteThread.execute(ExecuteThread.java:137)
at weblogic.kernel.ExecuteThread.run(ExecuteThread.java:120)Thanks Joe, your answer pointed me in the right direction. Just in case anyone
wants to know, the solution took two changes:
CHANGE
cStat.registerOutParameter(1, java.sql.Types.OTHER);
TO
cStat.registerOutParameter(1, oracle.jdbc.driver.OracleTypes.CURSOR);
(cStat is an instance of weblogic.jdbc.pool.CallableStatement)
AND
rs = cStat.getResultSet(1);
TO
rs = cStat.getCursor(1);
Thanks again,
Matt
Joseph Weinstein <[email protected]> wrote:
Hi Matt.
Look at the Oracle thin driver documentation to determine what type you
should define in the registerOutParameter call. We use 'OTHER', but
their driver may use something else for CURSOR output parameters.
joe
Matt Savino wrote:
Is it possible to retrieve a cursor bound to an out parameter whenusing the thin
driver to establish the connection pool to the database? I am currentlyusing
the JDriver to connect create the pool and the pool driver to connectfrom the
app to the connection pool. We'd like to avoid using the Oracle clientif possible.
Currently I register the out parameter as java.sql.Types.OTHER, thencall getResultSet(1)
on the weblogic.jdbc.pool.CallableStatement object. But it breaks whenI change
the connection pool to use the thin driver. The error is at the bottomof this
post.
I think I could possibly get the current pool driver to work if canfind some
documentation on these two methods:
void registerOutParameter(int i, int j, int k, int l)
void registerOutParameter(int i, int sqlType, java.lang.String typeName)
I have no idea what to put in for the ints in the first method or forsqlType
or typeName. Can anyone point me to where I can find this documentation?
E-docs mentions this class: weblogic.jdbc.vendor.oracle.OracleCallableStatement.
(http://edocs.bea.com/wls/docs61/jdbc/thirdparty.html#1023867). Should
I consider
this? If so where is it?
Thanks a lot,
Matt Savino
<<< error when using thin driver >>>
preparing callable stmt
callable stmt prepared, java.sql.Types.OTHER = 1111
java.sql.SQLException: Invalid column type
at oracle.jdbc.dbaccess.DBError.throwSqlException(DBError.java:168)
at oracle.jdbc.dbaccess.DBError.throwSqlException(DBError.java:210)
at oracle.jdbc.dbaccess.DBError.throwSqlException(DBError.java:273)
at oracle.jdbc.driver.OracleStatement.get_internal_type(OracleStatement.java:4560)
at oracle.jdbc.driver.OracleCallableStatement.registerOutParameter(OracleCallableStatement.java:225)
at oracle.jdbc.driver.OracleCallableStatement.registerOutParameter(OracleCallableStatement.java:350)
at weblogic.jdbc.pool.Statement.registerOutParameter(Statement.java:617)
at jsp_servlet._reportmanager.__thin_outputresultset._jspService(__thin_outputresultset.java:145)
at weblogic.servlet.jsp.JspBase.service(JspBase.java:27)
at weblogic.servlet.internal.ServletStubImpl.invokeServlet(ServletStubImpl.java:263)
at weblogic.servlet.internal.ServletStubImpl.invokeServlet(ServletStubImpl.java:200)
at weblogic.servlet.internal.WebAppServletContext.invokeServlet(WebAppServletContext.java:2390)
at weblogic.servlet.internal.ServletRequestImpl.execute(ServletRequestImpl.java:1959)
at weblogic.kernel.ExecuteThread.execute(ExecuteThread.java:137)
at weblogic.kernel.ExecuteThread.run(ExecuteThread.java:120)
PS: Folks: BEA WebLogic is expanding rapidly, with both entry and advanced
positions
for people who want to work with Java, XML, SOAP and E-Commerce infrastructure
products.
We have jobs at Nashua NH, Liberty Corner NJ, San Francisco and San Jose
CA.
Send resumes to [email protected] -
Unable to get the expected results with connection pooling
Hi All,
I have been trying to create JDBC connection pooling provided by the Apache Tomcat 4.0 with MySQL 4.0.16-nt at http://jakarta.apache.org/tomcat/tomcat-4.1-doc/jndi-datasource-examples-howto.html and my configuration is as follows
server.xml
<Context path="/DBTest" docBase="DBTest"
debug="5" reloadable="true" crossContext="true">
<Logger className="org.apache.catalina.logger.FileLogger"
prefix="localhost_DBTest_log." suffix=".txt"
timestamp="true"/>
<Resource name="jdbc/TestDB"
auth="Container"
type="javax.sql.DataSource"/>
<ResourceParams name="jdbc/TestDB">
<parameter>
<name>factory</name>
<value>org.apache.commons.dbcp.BasicDataSourceFactory</value>
</parameter>
<!-- Maximum number of dB connections in pool. Make sure you
configure your mysqld max_connections large enough to handle
all of your db connections. Set to 0 for no limit.
-->
<parameter>
<name>maxActive</name>
<value>100</value>
</parameter>
<!-- Maximum number of idle dB connections to retain in pool.
Set to 0 for no limit.
-->
<parameter>
<name>maxIdle</name>
<value>30</value>
</parameter>
<!-- Maximum time to wait for a dB connection to become available
in ms, in this example 10 seconds. An Exception is thrown if
this timeout is exceeded. Set to -1 to wait indefinitely.
-->
<parameter>
<name>maxWait</name>
<value>10000</value>
</parameter>
<!-- MySQL dB username and password for dB connections -->
<parameter>
<name>username</name>
<value>javauser</value>
</parameter>
<parameter>
<name>password</name>
<value>javadude</value>
</parameter>
<!-- Class name for mm.mysql JDBC driver -->
<parameter>
<name>driverClassName</name>
<value>org.gjt.mm.mysql.Driver</value>
</parameter>
<!-- The JDBC connection url for connecting to your MySQL dB.
The autoReconnect=true argument to the url makes sure that the
mm.mysql JDBC Driver will automatically reconnect if mysqld closed the
connection. mysqld by default closes idle connections after 8 hours.
-->
<parameter>
<name>url</name>
<value>jdbc:mysql://localhost:3306/javatest?autoReconnect=true</value>
</parameter>
</ResourceParams>
</Context>
web.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
<description>MySQL Test App</description>
<resource-ref>
<description>DB Connection</description>
<res-ref-name>jdbc/TestDB</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
</web-app>
test.jsp
<jsp:useBean id="foo" class="foo.DBTest" scope="page" />
<html>
<head>
<title>DB Test</title>
</head>
<body>
<%
foo.DBTest tst = new foo.DBTest();
tst.init();
%>
<h2>Results</h2>
Foo <%= tst.getFoo() %>
Bar <%= tst.getBar() %>
</body>
</html>
DBTest.java package
package foo;
import javax.naming.*;
import javax.sql.*;
import java.sql.*;
public class DBTest {
String foo = "Not Connected";
int bar = -1;
public void init() {
try{
Context ctx = new InitialContext();
if(ctx == null )
throw new Exception("Boom - No Context");
DataSource ds =
(DataSource)ctx.lookup(
"java:comp/env/jdbc/TestDB");
if (ds != null) {
Connection conn = ds.getConnection();
if(conn != null) {
foo = "Got Connection "+conn.toString();
Statement stmt = conn.createStatement();
ResultSet rst =
stmt.executeQuery(
"select id, foo, bar from testdata");
if(rst.next()) {
foo=rst.getString(2);
bar=rst.getInt(3);
conn.close();
}catch(Exception e) {
e.printStackTrace();
public String getFoo() { return foo; }
public int getBar() { return bar;}
Now when I am trying to run this on browser, everything goes fine except it doesn't show the expected results, instead of that it shows following in the browser:-
Results
Foo Not Connected
Bar -1
Can anybody help me out as to why I am getting such result while everything is right from my side. Is the program unable to connect to the database or it is not supporting the JDBC version that I am using.
Thanks in advance
Regards
VikasOh, I think this is not the right place to post this message. I have placed the same in other place of this forum. please ignore this post here!!
MJ, by the way the link that you suggested is not useful to me.
Thank you -
Hi Guys, can you please help me with Connection Pooling.
I have:-
Tomcat 5.0.27
MySQL 4
Apache 2.0.
JSP web pages.
I have been trying to get connection pooling working but i havent been successful yet. Please do help me make it happen.
I have posted my server.xml and web.xml from /conf/. They are not edited. I have also included the pages that I am currently ussing to connect to the database.
I need you to assist me with how I should edit the above.
1. SERVER.XML
Where and how should I edit this file?
2. WEB.XML
Where and how should I edit this file?
3. DATABASE_INFO.JSP
<%
Class.forName("com.mysql.jdbc.Driver").newInstance();
%>
<%!
public java.sql.Connection dataconnect() throws SQLException {
Connection database_connector;
database_connector = DriverManager.getConnection("jdbc:mysql://localhost/publications?user=hello&password=hello");
return database_connector;
%>
<%!
public java.sql.Connection adminconnect(javax.servlet.http.HttpSession session) throws SQLException {
Connection database_connector;
if (session.getAttribute("s_conn")!=null) {
database_connector = (Connection) session.getAttribute("s_conn");
if (database_connector.isClosed()) {
database_connector = DriverManager.getConnection("jdbc:mysql://localhost/publications?user=hello&password=hello");
} else {
database_connector = DriverManager.getConnection("jdbc:mysql://localhost/publications?user=hello&password=hello");
session.setAttribute("s_conn", database_connector);
return database_connector;
%>
<%!
public String filedir() {
String directory = "C:/Tomcat/webapps/ROOT/publications/";
return directory;
%>
etc
Database Name : publicationsHi,
1- put your jdbc driver jar file in $CATALINA_HOME/common/lib (ex: C:\tomcat\common\lib )
2- Next, modify the web application deployment descriptor (/WEB-INF/web.xml) to declare the JNDI name under which you will look up preconfigured data source
take care of the ordering as below so resourc-ref tag is after taglib
<resource-ref>
<description>
Resource reference to a factory for java.sql.Connection
instances that may be used for talking to a particular
database that is configured in the server.xml file.
</description>
<res-ref-name>
jdbc/EmployeeDB
</res-ref-name>
<res-type>
javax.sql.DataSource
</res-type>
<res-auth>
Container
</res-auth>
</resource-ref>
3- add an element like this to the /META-INF/context.xml file in the web application. ( under ../webapps/mywebapplication/WEB-INF
<Context ...>
<Resource name="jdbc/EmployeeDB" auth="Container"
type="javax.sql.DataSource" username="hello" password="hello"
driverClassName="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost/publications"
maxActive="8" maxIdle="4"/>
</Context>
4- code sample
Context initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup("java:comp/env");
DataSource ds = (DataSource)
envCtx.lookup("jdbc/EmployeeDB");
Connection conn = ds.getConnection();
... use this connection to access the database ...
conn.close();
The default data source support in Tomcat is based on the DBCP connection pool from the jakarta commons
Regards,
Alan Mehio
London,UK -
Weblogic 9.2 - Problem with Connection Pool not releasing resources
We have a third party application that is running Weblogic 9.2 and has a connection pool to a SQL 2005 db for queries within it's batch process. What I have noticed is that it does not seem to be releasing SQL cpu back after the batch and this is causing issues with processes for other dB's within the instance. Has anyone encountered this issue and if so what is the solution (short of isolating it within it's own instance). Can the connection be reset to release resources?
Yes it is a weblogic connection pool. What I mean is that when a batch run I can see the CPU for the SQL process associated with the connection increase but when the batch is completed the CPU remains high when I would expect it to move back down to an 'idle' level as after that as all it would be doing is the occasional "select 1' ping to keep the connection active.
What i do see is that the cpu in activity monitor shows high cpu and it never goes down unless the connection is killed and re-established. As this is a shared instance other apps are complaining of slow running procs. -
Jdbc-odbc bridge with Connection pool datasource
I have created a little j2ee app in which an enterprise bean accesses a ms sql server table by creating a JNDI datasource using sun.jdbc.odbc.JdbcOdbcDriver. I can successfully deploy it and run it on the jsdkee 1.3 J2EE server. However, when I attempt to deploy it on WebSphere 4.0 AES, the app fails attempting to make the database connection. The error log states: "Unable to connect to database: the class (sun.jdbc.odbc.JdbcOdbcDriver) does not implement javax.sql.ConnectionPoolDatasource or javax.sql.XADatasource". Which, of course, is probably true, but is there a WebSphere workaround? There is nothing remotely related mentioned at the IBM WebSphere site.
Thx. So far, I have not found a readily accessible free alternative driver that supports connection pooling. The drivers list notes several corporate offerings that do; freetds may work but I don't know yet. If it does, I will update this discussion.
-
Lots of TIME_WAITs with Connection Pool and Oracle
Hi,
I've set up a simple servlet to hit a database and have been running
some stress tests against it. Even if I limit the connection pool size
to a fixed number of connections, when I run netstat I get lots of
additional connections to the database machine showing up in the
TIME_WAIT state. The original connections from the pool are still there
as ESTABLISHED. Can anyone tell me where all the other ones are coming
from. I've tried using both oracle thin and oci8 drivers but I still
get the same problems.
Cheers,
Luke.
Luke Taylor.
PGP Key ID: 0x57E9523Ccheck out
1. the code is releasing the connections it got?
2. are there any database connections from outside the weblogic pool.
Luke Taylor <[email protected]> wrote:
Hi,
I've set up a simple servlet to hit a database and have been running
some stress tests against it. Even if I limit the connection pool size
to a fixed number of connections, when I run netstat I get lots of
additional connections to the database machine showing up in the
TIME_WAIT state. The original connections from the pool are still there
as ESTABLISHED. Can anyone tell me where all the other ones are coming
from. I've tried using both oracle thin and oci8 drivers but I still
get the same problems.
Cheers,
Luke.
Luke Taylor.
PGP Key ID: 0x57E9523C -
Configuring JTA with connection pool
Hi all,
I need a sanity check here. I want to have the container manage the transactions
on my stateless session beans. I am connecting to a single database (no distributed
transactions needed) and want to use connection pooling.
I am using JNDI to get a reference to DataSource and then using the DataSource
to get connections. I am confused about whether I need to use an XA driver in
order to use the JTA.
How do I need to configure my connection pool such that the JTA will manage my
transactions against a single database? I am using either the Oracle 8i thin
driver or the Sybase jconn2.jar driver.
Thanks.
Alan Beaulieu wrote:
> Hi all,
>
> I need a sanity check here. I want to have the container manage the transactions
> on my stateless session beans. I am connecting to a single database (no distributed
> transactions needed) and want to use connection pooling.
>
> I am using JNDI to get a reference to DataSource and then using the DataSource
> to get connections.
You want to ensure that this is a TxDataSource (configured via the WebLogic console),
and not a plain, non-JTA aware DataSource.
> I am confused about whether I need to use an XA driver in
> order to use the JTA.
>
No.
>
> How do I need to configure my connection pool such that the JTA will manage my
> transactions against a single database? I am using either the Oracle 8i thin
> driver or the Sybase jconn2.jar driver.
>
TxDataSource is the key.
-- Rob
>
> Thanks.
-
Reg:Problem with Connection Pool
Hi all,
I copied DAc analysis RPD from the link (http://www.rittmanmead.com/2009/01/analyzing-bi-apps-etl-runs-using-obiee-and-the-dac-repository/ ) into my existing RPD by changing the connection pool of DAC Analysis RPD to the connection pool settings of my Existing RPD.
W_ETL_DEFN,W_ETL_DEFN_RUN,W_ETL_FOLDER,W_ETL_GROUP_STEP,W_ETL_PHASE,W_ETL_RUN_STEP,W_ETL_STEP,S_ETL_DAY
All these tables are coming from a schema BISchema.. Except S_ETL_DAY table. it is coming from the Usage Tracking tables and all the tables in the Usage tracking are coming from OBIAPP Schema.
In order to know about the ETL Runs Over time we need S_ETL_Day table..
So how do I import S_ETL_Day table to DAC folder..where the Schema of both DAC tables and Usage tracking table is Different.
Need Help....that you can do but there is a way to use that S_ETL_DAY table in do a double mapping in the BMM layer so that you can those fields in that particular table...
Maybe you are looking for
-
Module Pool Programming using Abap Objects
Hi gurus., I need to create a module pool program with tabstrips and tablecontrols using Abap objects...plz guide me how i can achieve this... i am very much confused.. i dont know how and where to start .. plz send me documents and sample codes rela
-
How to call the DLL writing in Vb6.0 from testsatnd?
Hi, I want to call a dll writting in VB6.0 from teststand. But as i see from the "Step Setting" in teststand, only the C/C++ Dll can be selected in the "adapter" type. I try to use this one as my adapter to call my VB6.0 dll, in result, there is no f
-
Flash Builder 4.7, eGit and the 'Label Decorations'
Used 4.6 along with eGit and there were little arrows if you were pushes or pulls behing your remote tracking branch. Now with 4.7 they are gone. Looked it up under Preferences->Team->Git->Label Decorations->Text Decorations and the { branch_status}
-
Itunes/QT converts video from sound to no-sound
I have a video that has sound. when i convert it for ipod or when I convert in QT to ipod, it ends up converted with no sound. Any thoughts? Thanks!
-
Everything is broke! gstreamer, pidgin [SOLVED]
Whats going on with arch? its not a bleeding edge anymore, its "fix you system after each upgrade" :\ First I had a lot of errors from ldconfig that /usr/lib/libgstX is bad because ELF header does not contain a good magic number (something like this)