Singleton in servlet

Hi,
I am using the singleton design pattern in some places to insure unicity and access to some "global" data. However, I am now designing a few servlets where I would need this pattern but applied to a Session.
My goal is to insure unicity of some storage object for my servlet, without having to pass them to all my classes.
Any tips? Any patterns? Any "singleton" equivalent for a Session in a servlet?
Any code sample would make my day!
Thanks!

I think you're on the wrong way.
If you wan to insure unicity of a data object in a servlet context, why don't you just create a singleton class an initialize it in the serlvet init()?

Similar Messages

  • Confused about singletons in servlets

    Hello,
    A DatabaseManager object is to be created within my RegistrationServlet. I wish to implement this DatabaseManager class as a singleton. I understand how the first client that invokes the RegistrationServlet will be able to create an instance of the DatabaseManager. However, what happens when a second client invokes the RegistrationServlet while the first client is still using the DatabaseManager instance? What is the best way to deal with this? Is an exception thrown?
    Thanks.

    Depends on how you implement the Singleton, of course.
    A Singleton might be a bad idea. Sounds like a bottleneck waiting to happen.
    That's a database isolation issue. It doesn't belong in a servlet. It belongs in a persistence layer.

  • Load on startup servlet and references

              Weblogic 6.1 SP2
              No jars specified in the classpath. A Singleton is located in a utility.jar file
              inside a .ear file.
              If I create a Singleton from a load on startup servlet, how long will the singleton
              be around? I know that if I undeploy the application, the singleton will be destroyed
              since the classloader is unloaded. However, if I never undeploy my application,
              will the Singleton always be around? Does Weblogic keep a reference alive to
              this Singleton forever?
              Please provide some more details on this!
              Thanks.
              Dan
              

              Dan Baumbach wrote:
              > So, because the startup servlet has a static reference to the singleton, the servlet
              > will never be garbage collected?
              Correct.
              >
              >
              > What if there's a class that is not a singleton, but there are static methods.
              > How would garbage collection work in this case?
              >
              A class object is not an instance object. If the class object has been loaded by the
              classloader, it will not be unloaded or garbage collected, regardless of whether or not
              it has static methods. If an instance of a class is instatiated on the heap, and a
              reference to that object is placed in a static member of its associated class object,
              also referred to as a class member, then the instance will not be garbage collected.
              >
              > Thanks.
              > Dan
              >
              > William Kemp <[email protected]> wrote:
              > >The jvm will not garbage collect an object that has a static reference
              > >to it. Which is how
              > >I am assuming you have implemented the singleton.
              > >
              > >Bill
              > >
              > >Dan Baumbach wrote:
              > >
              > >> Weblogic 6.1 SP2
              > >> No jars specified in the classpath. A Singleton is located in a utility.jar
              > >file
              > >> inside a .ear file.
              > >>
              > >> If I create a Singleton from a load on startup servlet, how long will
              > >the singleton
              > >> be around? I know that if I undeploy the application, the singleton
              > >will be destroyed
              > >> since the classloader is unloaded. However, if I never undeploy my
              > >application,
              > >> will the Singleton always be around? Does Weblogic keep a reference
              > >alive to
              > >> this Singleton forever?
              > >>
              > >> Please provide some more details on this!
              > >> Thanks.
              > >> Dan
              > >
              

  • A problem with annotation @EJB

    Hi,
    My application uses servlet+JSP+EJB+JBOSS. I want to use a pure java object that is a singleton and within this singleton call an EJB.
    I have a servlet that call a singleton:
    My servlet
    public class FindAdministratorForumServlet extends HttpServlet {
         private static final long serialVersionUID = 1L;
         // ======================================
         // = Entry point method =
         // ======================================
         @Override
         protected void service(final HttpServletRequest request,
                   final HttpServletResponse response) throws ServletException,
                   IOException {
              final int rows=3;
              int page = Integer.parseInt(request.getParameter("page"));
              List<Topic> discussionList = ListHandlerService.getForumTopics(page); My singleton :
    package service;
    import java.util.LinkedList;
    import java.util.List;
    import java.util.ListIterator;
    import javax.ejb.EJB;
    import sessionbean.TopicService;
    import entitybean.Topic;
    public class ListHandlerService {
         private final static int rows=3;
        /** L'instance statique */
        private static ListHandlerService instance;
        /** objet pour la synchronisation.
         * j'ajoute deux "soulignés" (__) au nom de l'attribut car il n'a
         * qu'un intérêt purement technique.
        private static Object objetSynchrone__;
        private static List<Topic> listTopic;
         @EJB
         private static TopicService discussionService;
        /** Récupère l'instance unique de la class Singleton.
        * Remarque : le constructeur est rendu inaccessible
        public static ListHandlerService getInstance() {
            if (null == instance) { // Premier appel
                synchronized(objetSynchrone__) {
                    if (null == instance) {
                        instance = new ListHandlerService();
            return instance;
        /** Constructeur redéfini comme étant privé pour interdire
        * son appel et forcer à passer par la méthode
        private ListHandlerService() {
        public static List<Topic> getForumTopics(int page) {
             int i = 0;
              Topic topic;
              LinkedList<Topic> result = new LinkedList<Topic>();
             if (page==1) {
                  listTopic = discussionService.getForumTopics();
                  ListIterator<Topic> listIterator = listTopic.listIterator();
                  while (listIterator.hasNext() && (i< rows)) {
                       topic = listIterator.next();
                       result.add(topic);
                       i++;
             } else {
                  ListIterator<Topic> listIterator = listTopic.listIterator();
                  while (listIterator.hasNext() && (i< rows*(page-1))) {
                       listIterator.hasNext();
                       i++;
                  while (listIterator.hasNext() && (i< rows*page)) {
                       topic = listIterator.next();
                       result.add(topic);
                       i++;
             return result;
        public static int getSize() {
             return listTopic.size();
    } In my singleton that is a pure JAVA object, the injection of my EJB with annotation @EJB doesn't seem to work. Indeed when executing, "discussionService" that should be injected and initialized, is null. Isn't it possible to inject an EJB in a pure java object which is a singleton ?
    Thank you for your answers.

    Is it deployed in the same application?
    In they are not in the same application you need to use some other techniques. See the following thread for info:
    http://forums.sun.com/thread.jspa?threadID=5332558

  • The best place to put the global parameter

    hello:
    i am now studying the petstore1.3,and find that the global parameters are kept in the servlet context,i wonder if it is a good solution.in my project,i seldom use the servlet context,session context etc,i feel more like to put the global parameter in a singleton that is loaded when the app is started. i don't know where is the best place to put the global parameter,servlet context or singleton?

    thanks for your answer.
    1 do your mean that the singleton can be shared among the different "war"
    packages if both of them are within the same jvm?if yes,must they be in the
    same "ear" package?
    2 if my app is deployed in the weblogic cluster environment,which one can be
    shared? singleton or servlet context?

  • Servlets design - use singletons??

    I am building a servlet to handle incoming POST connections. The user can send information to be added to the database. I have a servlet to handle the HTTP connection and a seperate class to handle the database interaction.
    Currently the database class is a normal class and a new one is created in the init() method of the servlet. What is the best way to do this? Should the db class be a singleton or what should happen?
    Also I have a seperate servlet to handle a different type of request, this one is required to handle a request to send an automatic text message. It needs to access the database as well but it will have to create a new db object to do so...
    What are the advantages/disadvantages of using singletons in a servlet context? I understand that garbage collection is quite a serious overhead in a server environment so its best to reduce it.
    thanks for your time.

    Thanks for the reply. What are the performance considerations with using just one instance of a class? Lets say 10 requests come in at the same time that need to use the same methods in the singleton. Will they just sit and wait for it to become free?
    just be careful when using multithreadingCan this problem not be avoided my adding the synchronised keyword to the methods in the singleton class?

  • Clustering and Application/Servlet Singletons...Replicated?

    Are static servlet and instance attributes replicated to servlet instances
              in cluster?
              We have seen some behavior which suggest no?
              Assuming all instance and static variables are serializable or atomic types,
              are they replicated?
              If not, how is application/servlet level state replicated? servletcontext?
              -phil ([email protected])
              [Phillip A. Lindsay.vcf]
              

    "Phillip A. Lindsay" wrote:
              > Are static servlet and instance attributes replicated to servlet instances
              > in cluster?
              Each node will have its own class/classloader tuple and therefore its own set
              of static and instance attributes. The singleton effect can be achieved by
              binding
              an object into a namespace at a well-known point. It can be argued that a
              singleton
              should be replicated but then it wouldn't be a "single" singleton.
              Cheers
              Alex
              mailto:[email protected] // Consulting services available
              

  • Singleton shared by Servlets & Class sharing

    Dear Gurus,
              I have
              A. a servlet that handles POST from http
              B. a validation class that validates data
              C. and a displayMessage servlet
              D. and a singleton MESSAGE class
              Servlet PostHandler instanciates MESSAGES singleton and calls validaiton
              class B, which validates accesses and puts messages into MESSAGES and calls
              C.
              now here's the problem,
              I get two instances of singleton, one for servlets and one for classes.
              I wonder if this is due to separate classloaders for servlets and regular
              classes.
              Can this be done or should we change the design ?
              Help appreciated,
              Thanx,
              Div
              

    [Crossposted at SO|http://stackoverflow.com/questions/1770610/jsf-session-scoped-bean-shared-by-browsers-on-different-machines].

  • Servlet life cycle/Singleton pattern/synchronized

    I have some questions about the life cycle of a servlet and the use of synchronozed.
    We have a main controller class that is extended from HTTPServlet and accepts all HTTP requests. It in turn instantiates another class to do the work. That class eventually returns control to the main controller and the request is forwarded. It is a typical MVC.
    1. Once the helper class is instantiated how long will it live? We never destroy the class. I can debug the class using JBuilder and see variables set from the previous access.
    2. While the class is in memory, if two or more requests are requiring the use of it, is a copy of the class created and used by each request. These particular classes are not instantiated as 'private static' instances.
    3. If no copy is made, will the requests wait for the other to finish its processing before it gains control of the class. If no, I am assuming that proper use of synchronized will eliminate any issues.
    4. Anyone have advice on where and when to synchronize or do you know of any good articles on this topic.
    Thanks in advance for any advice you can give.

    Hello,
    Many of your question depends on where you declare the helper class, so here it goes:
    1) The helper class will stay in memory as long as it's scope lasts. Ie: If you declare it as an instance member of the servlet it will stay alive until the servlet is unloaded by the application engine.
    2) In short, local and parameter members, yes. Instance members no.
    3) Most servlet configurations servers multiple requests on the same servlet. So if your helper class is an instance member it can be accessed be multipe threads at the same time. You can also declare that your servlet is not thread safe and the application engine will create multiple copies of it instead.
    4) Er... Have a look around. I'm sure there are several examples and tutotrials on this site alone.
    Yours
    - Lars J. Nilsson

  • HA Singleton Servlet - JMS

    Hello All,
    I have an issue when i try to invoke JMS application from a servlet. In the servlet i have set the configuration to start the servlet during the application server startup. When the servlet start it invokes JMS application (not MDB).
    Problem is when JMS application starts, lookup of ConnectionFactory fails since java:/JmsXA binding has still not happened. Meaning, before the application server binds with JmsXA , JMS tries to lookup causing the failure.
    Please provide how to handle this.
    Thanks.

    Hisham <[email protected]> wrote:
              > Hi, I've read ... that one can do JMS from a C/C++ client by
              > using a servlet.
              Sure, it's possible. There's other ways, too.
              Hisham <[email protected]> wrote:
              > I am not too familiar with C network programming, so
              > can anyone here provide some guidance or pointers for implementing
              > this C client.
              I like that "pointers" pun! Seriously, you may want to get involved
              with learning the basic of C/C++ network (socket) programming before
              attempting to implement this client.
              Hisham <[email protected]> wrote:
              > What libraries should be used? I would prefer to use
              > the https protocol. Any online references or sample code is
              > appreciated!!
              Here's something that I've heard was quite nice: JMS Courier (I think
              they're at release 1.1 these days). It works on both Solaris and
              Windows platforms. Basically, it's a big C++ class library. The
              concept is simple -- the C++ bindings access Java, thus providing all
              the cool JMS functionality for you C++ application.
              Let me know how it goes...
              Brian J. Mitchell
              BEA Systems Administrator
              TRX
              Atlanta, GA
              email: [email protected]
              office: 404-327-7238
              mobile: 678-283-6530
              

  • Shared Connection Pool via Singleton

    I have just started to learn Java (more jsp & servlets) and have been going through "Core Servlets and Java Server Pages" and in there is stuff on connection pooling. The author provides a good a connection pool servlet that can be shared, but as I'm new and don't fully understand how everything works (got a basic idea).
    How do i go about making the following code accessiable via a singleton class?
    ConnectionPool Class
    package sco;
    import java.sql.*;
    import java.util.*;
    /** A class for preallocating, recycling, and managing
    *  JDBC connections.
    *  <P>
    *  Taken from Core Servlets and JavaServer Pages
    *  from Prentice Hall and Sun Microsystems Press,
    *  http://www.coreservlets.com/.
    *  &copy; 2000 Marty Hall; may be freely used or adapted.
    public class ConnectionPool implements Runnable {
      private String driver, url, username, password;
      private int maxConnections;
      private boolean waitIfBusy;
      private Vector availableConnections, busyConnections;
      private boolean connectionPending = false;
      public ConnectionPool(String driver, String url,
                            String username, String password,
                            int initialConnections,
                            int maxConnections,
                            boolean waitIfBusy)
          throws SQLException {
        this.driver = driver;
        this.url = url;
        this.username = username;
        this.password = password;
        this.maxConnections = maxConnections;
        this.waitIfBusy = waitIfBusy;
        if (initialConnections > maxConnections) {
          initialConnections = maxConnections;
        availableConnections = new Vector(initialConnections);
        busyConnections = new Vector();
        for(int i=0; i<initialConnections; i++) {
          availableConnections.addElement(makeNewConnection());
      public synchronized Connection getConnection()
          throws SQLException {
        if (!availableConnections.isEmpty()) {
          Connection existingConnection =
            (Connection)availableConnections.lastElement();
          int lastIndex = availableConnections.size() - 1;
          availableConnections.removeElementAt(lastIndex);
          // 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.isClosed()) {
            notifyAll(); // Freed up a spot for anybody waiting
            return(getConnection());
          } else {
            busyConnections.addElement(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 SQLException("Connection limit reached");
          // 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) {}
          // Someone freed up a connection, 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);
          connectThread.start();
        } catch(OutOfMemoryError oome) {
          // Give up on new connection
      public void run() {
        try {
          Connection connection = makeNewConnection();
          synchronized(this) {
            availableConnections.addElement(connection);
            connectionPending = false;
            notifyAll();
        } catch(Exception e) { // SQLException or OutOfMemory
          // Give up on new connection and wait for existing one
          // to free up.
      // This explicitly makes a new connection. Called in
      // the foreground when initializing the ConnectionPool,
      // and called in the background when running.
      private Connection makeNewConnection()
          throws SQLException {
        try {
          // Load database driver if not already loaded
          Class.forName(driver);
          // Establish network connection to database
          Connection connection =
            DriverManager.getConnection(url, username, password);
          return(connection);
        } catch(ClassNotFoundException cnfe) {
          // Simplify try/catch blocks of people using this by
          // throwing only one exception type.
          throw new SQLException("Can't find class for driver: " +
                                 driver);
      public synchronized void free(Connection connection) {
        busyConnections.removeElement(connection);
        availableConnections.addElement(connection);
        // Wake up threads that are waiting for a connection
        notifyAll();
      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();
      private void closeConnections(Vector connections) {
        try {
          for(int i=0; i<connections.size(); i++) {
            Connection connection =
              (Connection)connections.elementAt(i);
            if (!connection.isClosed()) {
              connection.close();
        } catch(SQLException sqle) {
          // Ignore errors; garbage collect anyhow
      public synchronized String toString() {
        String info =
          "ConnectionPool(" + url + "," + username + ")\n" +
          ", available=" + availableConnections.size() + "\n" +
          ", busy=" + busyConnections.size() + "\n" +
          ", max=" + maxConnections;
        return(info);
    ScoPool Class (singleton to access the connection pool)
    package sco;
    public class ScoPool extends ConnectionPool {
      private ScoPool pool = null;
      private ScoPool() {
        super(); // Call parent constructor
      public static synchronized ScoPool getInstance() {
        if(pool == null) {
          pool = new ScoPool();
        return(pool);
    }Please help a newbie.

    Figured it out.
    package sco;
    import java.sql.SQLException;
    public class ScoPool extends ConnectionPool {
      private static ScoPool pool;
      private ScoPool(String driver, String url, String username, String password,
                      int initialConnections, int maxConnections, boolean waitIfBusy) throws SQLException {
        super(driver, url, username, password, initialConnections, maxConnections, waitIfBusy); // Call parent constructor
      public static synchronized ScoPool getInstance() {
        if(pool == null) {
          String driver = "com.microsoft.jdbc.sqlserver.SQLServerDriver";
          String url = "jdbc:microsoft:sqlserver://MIM-W0432:1433;DatabaseName=sco";
          String username = "sco_user";
          String password = "123";
          int initCon = 5;
          int maxCon = 10;
          boolean waitIfBusy = true;
          try {
            pool = new ScoPool(driver, url, username, password, initCon, maxCon, waitIfBusy);
          catch(SQLException sqle) {
        return pool;
    }

  • Do I need to synchronize a singleton just for reads?

    Hello forum. Here's my situation: I keep config data for pages on my website in an XML file, I load said XML file in a startup servlet, creating a JDOM Document object, accessed by a singleton.
    Every time a page is loaded, the page accesses this Document object via the singleton, sees whether the page is secure, which template it should use, a bunch of stuff.
    Now, because the Document object is created when the context is started, and is never written too, only read, do I need to synchronize it?
    I read "Threading lightly, Part 1: Synchronization is not the enemy," on ibm.com (http://www-128.ibm.com/developerworks/java/library/j-threads1.html) in hopes of answering my own question, and the most relevant paragraph states:
    "If you are writing data that may be read later by another thread, or reading data that may have been written by another thread, then that data is shared, and you must synchronize when accessing it."
    But does my scenario fit? Yes I'm writing data that will be read by another thread, but no thead is accessing this data until the context is fully loaded and the object is fully instantiated. The object is not being written to by threads asynchronously... I just run the risk of it being read at the same time. Do I need to synchronize? If so... having synchronized variables in a servlet environment is bad, so what other approach should I take?
    Thanks for your help.

    But does my scenario fit? Yes I'm writing data that
    will be read by another thread, but no thead is
    accessing this data until the context is fully loaded
    and the object is fully instantiated. The object is
    not being written to by threads asynchronously.If all the writing is complete before any of the reading starts, then there's no need to synchronize the reading.
    .. I
    just run the risk of it being read at the same time.There's no risk in multiple concurrent reads.
    Do I need to synchronize? If so... having
    g synchronized variables in a servlet environment is
    bad, so what other approach should I take?Couple minor points:
    * You don't have synchronized variables. You have synchronized blocks and methods.
    * Using synchronization in a servlet context isn't in and of itself necessarily bad. Having multiple requests sync on the same lock can hurt response time, so try to avoid it, and if you must do it, keep the critical sections as small as possible.

  • Error when @Singleton in Glassfish v3 and weld. CDI not working for EJBs.

    Hello,
    I am getting the following error when deploying a web app with a SSB with the @Singleton annotation. If I use javax.ejb.Singleton I get the error. If I use @Stateless and @Singleton with javax.inject.Singleton, I don't.
    I use Glassfish v3 with weld.
    [#|2009-12-19T01:29:19.423+0100|SEVERE|glassfish|global|_ThreadID=16;_ThreadName=Thread-1;|The annotation symbol defined in super-class is not compatible with Session ejb ElaphusManager.
    symbol: TYPE location: class com.cervatoh2.elaphus.ejb.ElaphusManagerBean
    By the way,
    what is the right way to install weld into glassfish? To make @Named work I had to treat Glassfish v3 as if it was Tomat:
              <listener>
                        <listener-class>org.jboss.weld.environment.servlet.Listener</listener-class>
                   </listener>
              <resource-env-ref>
    <description>Object factory for the CDI Bean Manager</description>
    <resource-env-ref-name>BeanManager</resource-env-ref-name>
    <resource-env-ref-type>javax.enterprise.inject.spi.BeanManager</resource-env-ref-type>
    </resource-env-ref>
    And also add weld-servle.jar to /WEB-INF/lib
    isn't Glassfish v3 supposed to have builtin weld support?
    thanks for any directions,
    Ignacio

    Well,
    I think I have understood what the problem is, and maybe also a patch for it.
    I have observed the exact same scenario as you guys.
    I think the problem is exposed by the statement in the status.conf file:
    rwConnStart message=All 1 wget requests did not return a valid vpnserver.conf
    The contents of the vpnserver.conf file in your case is:
    Which I also have observed. Now, I have just had a session, where one of my colleagues have a succesfull connection and I have a failed one. Now, his vpnserver.conf was:
    version=1
    msgtype=configuration
    conn xxxxx_rw
    presharedkey=xxxxxxxxxxxxxxxxxxx
    rightsubnet=xxx.xxx.xxx.xxx/xx
    remotelanip=xxx.xxx.xxx.xxx
    dnsserver=xxx.xxx.xxx.xxx
    domain=
    which is somewhat different. Mine was like the failing one you had. This made me think. The client is supposed to download vpnserver.conf via HTTPS and save it. Sometimes this goes wrong, and I think it is the router software that gets confused.
    It simply thinks you are trying to remote mgmt it and sends you the html to go to the welcome.html page. In my setup I have enabled HTTPS and disbaled Remote MGMT. So it should never ever think it is being remotely managed, but somehow it does that - doh!
    Thus, either the SW on the router is confused/buggy and this causes it to give you a HTML respond instead of the contents of the vpnserver.conf file. Another explanation could be that the wget tool has a problem, when a vpnserver.conf file already exists and then it doesn ensure to force download the file correctly or something.
    Nevertheless, I have two ways to solve this problem:
    1. Rebooting the router has worked for me, but is of course not nice
    2. Delete the local version of vpnserver.conf BEFORE you try to connect.
    The 2nd solution has not yet been verified to work in a broader scale, but we are trying to verify it.
    Please report if this helps you guys.
    Thanks, Jacob

  • Global variable in servlet & DBPooling questions

    Hello guys,
    I used to develop PHP/ASP, and am new to servlet. I have been searching around for a solution ...
    With Php, we can get the reference of a global variable in any classes->functions...
    How do I do this with servlet ?
    And second..I have developed the DB class as below... I set the datasource to be static, so it initializes only once. Is it a good idea? How would you like to improve this class? any comments?
    package shop.database;
    import javax.sql.DataSource;
    import java.sql.*;
    import org.apache.commons.dbcp.BasicDataSource;
    import org.apache.log4j.Logger;
    import shop.admin.exception.GeneralException;
    public class DdManager {
         static protected Logger logger = Logger.getLogger(DdManager.class);
         private String userName = "root";
    private String password = "";
    private String hostName = "jdbc:mysql://localhost:3306/shop";
    private String database="shop";
         static private DataSource ds;     // set this to be static so all threads share the same job in JVM
         private Statement stmt;
         private Connection conn;
         private ResultSet rs;
         private CallableStatement cs;
    public DdManager() {}
    * setup the data source and return it
         public static DataSource getDataSource(
              String sDrvName,
              String sUserName,
              String sPwd,
              String connectURI) {
              BasicDataSource ds = new BasicDataSource();
              ds.setDriverClassName( sDrvName );
              ds.setUsername( sUserName );
              ds.setPassword( sPwd );
              ds.setUrl( connectURI );
              ds.setMaxActive( 15 );
              ds.setMaxIdle( 10 );
              ds.setMaxWait( 10000 ); // 10 seconds
              return ds;
         * static init of the class
         * this class is will be called only once to initialize the DataSource
         static {
              try {
                   Class.forName( "com.mysql.jdbc.Driver" );
                   ds = getDataSource(     "com.mysql.jdbc.Driver",
                                            "root",
                                            "jdbc:mysql://localhost:3306/shop" );
                   if (ds == null) {
                        String msg = "Connection Pool error";
                        logger.error(msg);
                        throw new GeneralException(msg);
                   logger.info("DataSource has been initialized");
              } catch(Exception exception) {
                   logger.error(exception.toString());
                   try {
                        throw new GeneralException(exception.toString());
                   } catch (GeneralException e) {
                        logger.error(e.toString());
         * get the connection from the pool (DataSource)
    public void openConnection() throws GeneralException {
    try {
         BasicDataSource bds = (BasicDataSource) ds;
         logger.info("NumActive: " + bds.getNumActive() + ", " + "NumIdle: " + bds.getNumIdle());
    conn = ds.getConnection();
    logger.info("Connection of " + database + " has been established");
    } catch(Exception exception) {
         logger.error(exception.toString());
         throw new GeneralException(exception.toString());
    * close the connection will actually return the connection to the pool (Must)
    public void closeConnection() throws GeneralException {
         initResource();
    try {
         if (conn != null){
                   conn.close();
                   logger.info("Connection of " + database + " has been closed");
    } catch(SQLException exception) {
         logger.error(exception.toString());
         throw new GeneralException(exception.toString());
    * prepare the calling stmt
    public void prepareProcedure(String callStatement) throws GeneralException {
         initResource();
    try {
         cs = conn.prepareCall(callStatement);
    } catch(SQLException exception) {
         logger.error(exception.toString());
         throw new GeneralException(exception.toString());
    * set the pass-in parameter for "String"
    public void setParameter(int position, String parameter) throws GeneralException {
    try {
         cs.setString(position, parameter);
    } catch(Exception exception) {
         logger.error(exception.toString());
         throw new GeneralException(exception.toString());
    * set the pass-in parameter for "Integer"
    public void setParameter(int position, int parameter) throws GeneralException {
    try {
         cs.setInt(position, parameter);
    } catch(Exception exception) {
         logger.error(exception.toString());
         throw new GeneralException(exception.toString());
    * execute the procedure and return the resultset
    public ResultSet execProcedure() throws GeneralException {
    try {
         rs = cs.executeQuery();
    } catch(SQLException exception) {
         logger.error(exception.toString());
         throw new GeneralException(exception.toString());
    return rs;
    * close the statment and resultset
         private void initResource() throws GeneralException {
         try {
              if(rs != null) {
                   rs.close();
              if(stmt!= null) {
                   stmt.close();
              logger.info("Statement & Resultset have been free");
         } catch(Exception exception) {
         logger.error(exception.toString());
         throw new GeneralException(exception.toString());
    Thanks mates!
    myy

    Thanks Saish,
    Your response is really appreciated. Sorry about that
    as i didnt know there is 'code' formatting button,
    and I will look into the Singleton pattern.
    As I'm still in the learning stage. Therefore, i
    still have a lot of thing do not understand.
    ... use it in a method signature ...What is "a method signature" ?
    A method signature is basically the method's parameters, return value, name and any access or other modifiers. The following is a method signature:
    static final public void main(final String[] args)Between the braces of the method body is the implementation (or as I already alluded to, the method body).
    Consider using an already-developed connection poolimplementation, such as Jakarta Commons DBCP ...
    I'm trying to implement the Jakarta DBCP. Did I go
    into the wrong way?
    Sorry, did not read the imports. Yes, you are. However, I am confused about what you are trying to implement. You have a static method getDataSource(). You also have a static variable 'ds'. Use one or the other. I would be that there are seemingly random errors cropping up based on whether you remember to call getDataSource() or not.
    You do not, generally, want the data source to be static. Multiple threads might use the class. And if there is only a static data source, you will either need to synchronize the methods that use the data source (resulting in a scaling bottleneck) or not synchronize them (which will totally destroy any concept of a logical unit of work or database transaction).
    .. A static datasource, as in your class, can onlysafely be used by one thread at a time, potentially
    introducing scaling bottlenecks (or race conditions)
    in your system ...
    So, you mean there is no need for the DataSource to
    be static ?
    No, in fact, IMO, it should not be. That is why you are pooling. Use instances. The pool will manage the connections and their availabilty for you.
    Why are you throwing GeneralException everywhere?Here's a question: can someone using your class (a
    caller) realistically be expected to handle a
    database exception?
    When there is a database error, I just want to stop
    the process and redirect the user to an error page. I
    will look into the unchecked exceptions. Thanks.
    Unchecked exceptions do not need to be declared in a method signature or caught within the method body. Checked exceptions do. As such, an added benefit is that unchecked exceptions de-clutter your code.
    In your initResources() method, what happens if theclose() on ResultSet throws an exception
    Oh, yes. I'm so stupid.
    Now I only have ...
         private static DataSource ds;     // set this to
    be static so all threads share the same obj in JVM
         private Connection conn;
         private CallableStatement cs;
    private void initResource() throws GeneralException
    n {
         try {
              if(cs != null) {
                   cs.close();
    logger.info("CallableStatement has been
    as been free");
         } catch(Exception exception) {
         logger.error(exception.toString());
    throw new
    throw new GeneralException(exception.toString());
    You still have issues.
    public void initResources() {
       if (rs != null) {
         try { rs.close(); } catch (SQLException ignore) { ignore.printStackTrace(); }
       if (stmt != null) {
         try { stmt.close(); } catch (SQLException ignore) { ignore.printStackTrace(); }
    }Normally, this type of method would not be called initResources() but rather closeResources() or freeResources(). It would be called from within the 'finally' block of another method using the CallableStatement or ResultSet.
    This is really is problem, would you mind to tell me
    how to handle this(close the connection) if the
    close() on either CallableStatement or Resultset
    throws an exception ?
    See above. Simply log the exception (there is usually nothing meaningful you can do if a close() fails, and it is up to you as a developer if this is an error or just a warning). Another option is to 'chain' exceptions. In your own exception, add a method 'addException(Throwable)'. This would add another exception to a List of exceptions. When you print the stack trace, iterate through the chained exceptions to print them all out. One place where I find this useful is rollback() code. If the original SQL statement fails AND the rollback fails, I definitely want to see that rollback() exception as well in my logs.
    The DB thing makes me headache. What I actually
    wanted is a solution for:
    Let say I have a class "HelloAction.class" contains
    the code:
    public ActionForward XXX() {
         DbManager DB = new DBManager();
         ... do some DB thing here...
         SecondClass SC = new SecondClass();
         SC.doSomeOtherDbThing();
         ... do something else...
         ThirdClass TC = new ThirdClass();
         SC.doMoreOtherDbThing();
    }There are some functions in SecondClass.class and
    ThirdClass.class that will need database connection.
    I consider 'global variable' is because I want these
    two classes are able to use the same
    connection(DbManager) from the function -
    ActionForward XXX().
    What is the best way to implement the above situation
    (sharing the same connection in different classes &
    sub-classes?
    I also just realize that the problem of multi-threads
    with these two class variables..
         private Connection conn;
         private CallableStatement cs;Really headache. I really appreciate any comments.
    Thanks.
    - myyPass the Connection or DataSource to each method or constructor. Call commit() or rollback() from the method that created the transaction.
    - Saish

  • "Sharing" a stateful session bean between two servlets, beans

    Hello!
    I just started to learn some java ee programming and was wondering how i would share one stateful session bean between two servlets.
    I created the bean with @Stateful.
    I tried to inject the stateful bean in both servlets by @EJB and i can manipulate the object, but each servlet seems to have its own object.
    The bean has a remote interface that it implements.
    What i also tried was to add the mappedName to the @Stateful expression. Something like: @Stateful(mappedName="name") and to use the bean by @EJB(mappedName="name") but it had no effect.
    Im using glassfish 2.1 with netbeans 6.7.1 as my environment (standard settings)
    dummy question, but i googled like hours and couldnt find anything : \
    hope someone can help and sorry for my bad english
    greets and thanks

    Hi there!
    I think you are searching for something like an application wide singleton. There is the possibility to define such one in the Glassfish admin console.
    Hope this helps!

Maybe you are looking for

  • DB connect dump while creating structure

    Hi All, My source system is oracle, so we are using DB connect. In oracle system we created a View and i am trying to create datasource with that fields through RSDBC. i am able to see my view in RSDBC and then i tried to check the data by clicking "

  • Nokia E90 and Linux... how compatible are they?

    I am hoping to soon upgrade my current mobile phone (Nokia 6822) and separate PDA (a Palm Tungsten T3) to a Nokia E90. However, I have reservations... Does anyone have any knowledge or experience about how the Nokia E90 syncs with Linux Ubuntu? I kno

  • Reading Sheet name from csv file.

    Dear All, I am doing one program where i am reading contents from .csv file from oracle forms. I m using utl_file for reading the contents from .csv file. But problem is i am having 5 sheets under .csv file and i want to read fifth sheet's data. how

  • Wait Step, Exception Handling, Alerts

    Hi Everybody,              I am implementing a BPM scenario. I have a few questions: 1) The wait step i am using in BPm, allows me the min wait time as 1 min, can't I have lesser wait time then that. Lets say 30 secs. 2) Under what conditions should

  • Another ea4500 firmware bug

    today I have over 20 iphones connected to my router yet only two in the house. The MAC address bug seems to have gotten worse with the newest firmware.