Singleton or application scope?

Hi,we have a class that is accessed by all servlets and it is only created once.
We r discussing about making this class singleton or creating an instance and put it in the HttpSession in application scope. What alternative is better? Thanx in advance.

Just because you put a class in an application scope does not prevent someone from creating a second instance of that class. If the single instance property is of significant importance, than a singleton is probably the better way to go - you can guarantee that your variables exist only once. This seems like a better design. You could, of course, place this singleton instance in the application scope as well, therefore getting the benefits of both approaches.
Michael

Similar Messages

  • What are the pros and cons of storing heavely used CFCs in the application scope?

    I've been storing all the required CFCs for a site in the application scope. During onApplicationStart I do something like this application.objSomeCfc =CreateObject('component', 'com.someCfc').init().
    Here is my reasoning.
    Get the CFCs initialized once and stored in memory for better performance.
    Using CreateObject several times on each page load can have a negative impact on performance.
    Having one place to create application scoped CFCs makes it easier to manage code.
    So is my thinking flawed? Are there any additional pros or cons for dealing with CFCs? Is there any docs, articles, blogs, videos, frameworks, ...... that I should check that may change my perspective on how I'm doing this?
    Thanks

    Your approach is fine, depending on how many and what type of CFCs you are talking about. If they are "singletons" - that is, only one instance of each CFC is needed to be in memory and can be reused/shared from multiple parts of your application - caching them in the application scope is common.  Just make sure they are thread safe ("var" or local.* all your method variables).
    You might consider taking advantage of a dependency injection framework, such as DI/1 (part of the FW/1 MVC framework), ColdSpring, or WireBox (a module of the ColdBox platform that can be used independently).  They have mechanisms for handling and caching singletons.  Then you wouldn't have to go to the application scope to get your CFC instances.
    -Carl V.

  • Best Performance? - having a single stateless java pojo as delegate- give it application scope?

    I'm curious about which is best from a performance standpoint -<br /><br />All of our flex calls access a single java pojo. In my remoting-config.xml I'm currently declaring the destination a property scope of 'application': <br /><br /><destination id="UIServicesDelegate"><br />    <channels><br />      <channel ref="my-amf"/><br />      <channel ref="my-local-amf"/ <br />    </channels> <br />     <properties><br />        <factory>spring</factory><br />        <source>uiServicesDelegateBean</source><br />        <scope>application</scope><br />    </properties><br /></destination><br /><br />All of the UIServiceDelegate methods are stateless however, so I'm wondering if I'm gaining anything by giving it scope session. Since their all stateless I"m assuming application scope would be the best from a performance standpoint? I'm assuming in this case only one object will ever be instantiated? <br /><br />Assuming it was between Session and Request scope, is there a lot of overhead instantiating the new server side object each time? I would assume performance would be better using the Session in this case, with the only draw back of some server-side ram being chewed up storing the object in the Session. <br /><br />If you want "singleton" type approach, I figure just using application scope is the preferred approach?

    You wont get any api for directly accessing Servlet application objects from any ejb. I dont think MDB either solves your problem directly. Indirectly you can place a request to some servlet (should be there for each JVM and web application ) and update your application scope variable. I would suggest you to cache the data in database if the size of cache is large. otherwise any open caching tools may help you.

  • JWS Lifecycle/Scope (Axis "Application Scope" Behavior in WebLogic?)

    Apache Axis supports three different scopes for web services (Application, Request, Session). The documentation for Application scope says the following:
    <p>
    <i>"Application scope means there will only be a single instance of the service class for the entire AxisEngine. This means that that you, the developer of the service class must make sure all your methods are thread safe. ... Any state you keep in your service object will be shared across all invocations for the lifetime of the engine."</i>
    <p>
    How can I achieve the same behavior with a JWS service developed under WebLogic. ...a singleton web service accessed by multiple clients that maintains a shared state for the lifetime of the WebLogic server.
    <p>
    Thanks in advance,<br>
    Troy

    Apache Axis supports three different scopes for web services (Application, Request, Session). The documentation for Application scope says the following:
    <p>
    <i>"Application scope means there will only be a single instance of the service class for the entire AxisEngine. This means that that you, the developer of the service class must make sure all your methods are thread safe. ... Any state you keep in your service object will be shared across all invocations for the lifetime of the engine."</i>
    <p>
    How can I achieve the same behavior with a JWS service developed under WebLogic. ...a singleton web service accessed by multiple clients that maintains a shared state for the lifetime of the WebLogic server.
    <p>
    Thanks in advance,<br>
    Troy

  • Application scope bean Vs. EJB

    I want to cash some application data - and was thinking of using a singleton bean with application scope in my controller and JSP page.
    <jsp:useBean id="myBean" scope="application" class="bean.datacash" />
    I am not very familiar with EJBs - and wanted to know if it would be a mistake not to use an EJB to perform that task.
    Is there a downside to my approach?
    Thanks for any insight
    Mike

    Entity EJB'S are used as a kind of data persistence, mostly to Databases. In a way it's like a kind of cache but any changes you make to an EJB are usually persisted to the underlying data storage on a regular basis.
    Session EJB's are more for business logic and depending on the type of Session Bean you use can either remain persisted in a session state or used and thrown away.
    EJB's also require alot of code so depending on your application requirements it is kind of a big decision.
    Is the data your wanting to cache to be shared by all users using the application? Are there any race conditions that may be met by concurrent access to the data? What do you plan to do with the cached data store it in a database or just make it available to share?
    If you want to look into using EJB's then your going to require an EJB Container to run them in (this can be standalone like OpenEJB or as part of an J2EE Application server like JBoss or Oracle Application Server to name just a couple).
    Using the Singleton Javabean can keeps things simple but once you start to synchronize methods with multiple users you can find some slowing down of the logic as the singleton tries to complete a request before getting onto the next.
    The [url http://jakarta.apache.org]Jakarta team offer a package called commons pooling which is designed as a pooling framework (also a way of caching) that can come in handy, I've used it to create a custom JDBC Connection pooler and it works quite well when you get the hang of it.
    Another thing to consider is the load the application may be under at it's busiest time. How many concurrent users do you expect to access the application?
    Sorry I can't give you a real answer as that is entirely up to you and your requirements. If you have a small app that has around 20-50 users then EJBs are bit of an overkill. If you find you'll have 100+ users with lots of data to manage then EJB's are probably a good option.
    If you have a look at [url http://www.theserverside.com]the serverside web site you may find a couple of articles on data persistence or check out some of the online magazines which also have articles on this same topic.
    Anthony

  • Is Weblogic Cluster  supports Application scope Objects?

              Our Application is mainly depends on Application scope objects. On one m/c, it
              is perfect.
              Now, we want to support the failover , load balancing ... (High Availability).
              I know, weblogic cluster supports HttpSessions, EjbObjects ... etc. What about
              Application scope objects.
              we are planning for weblogic server which supports the our requirements.
              If not, what is the solution to make it work by using Weblogic server.
              for eg: I can give what type of application we are developing --- similar to
              textchat.
              our application is real time application.
              

    Even a singleton is not good enough as singletons are good only in the VM they were
              created it. One way is to have a distributed object such as a stateful session bean of
              which only one instance exists. U can create it at startup and store its handle in
              some persistent storage as well as a singleton. This ensures that even if the
              singleton doesnt contain it the refgerence to it can be obtained.
              There will be some problems with this setup as people should not allow it to create
              instances of it . Any such endeavor will lead to a CacheFullException.
              But essentially that seems possible.
              Even the 2.3 Servlet specification mandates that ServletContext and Application level
              object is only valid inside the JVM which created it. HttpSessions are replicated
              SessionContexts are not and are not likely to be in any J2EE application server
              Sameer
              Devi wrote:
              > One more comment from my side,
              > U mentioned "EXCEPT FOR JNDI" , if this is possible, how can we acheive?
              > Can U give brief description ? Take textchat example itself? since, our application
              > is almost have same mechanism. If it is < 1 sec delay means acceptable for this
              > release.
              >
              > Thanks,
              > Devi
              >
              > "Cameron Purdy" <[email protected]> wrote:
              > >Weblogic doesn't support replicated / synchronized app scope objects
              > >across
              > >a cluster except for JNDI, which is probably not a good solution for
              > >what
              > >you are describing.
              > >
              > >If you need a real-time shared fault-tolerant fail-overable high-performance
              > >load-balanced high-scale data store, then let me know when you find one
              > >;-)
              > >.... seriously, there are not a whole lot of good general purpose solutions
              > >in this space. There are some things to look at but they are all expensive:
              > >
              > >Persistent PowerTier on top of Oracle - a caching entity EJB server
              > >Jasmine (or whatever it is called this week) - an object oriented
              > >distributed data store
              > >....
              > >
              > >Peace,
              > >
              > >--
              > >Cameron Purdy
              > >Tangosol Inc.
              > ><< Tangosol Server: How Weblogic applications are customized >>
              > ><< Download now from http://www.tangosol.com/download.jsp >>
              > >
              > >
              > >"Devi" <[email protected]> wrote in message
              > >news:[email protected]...
              > >>
              > >> Our Application is mainly depends on Application scope objects. On
              > >one
              > >m/c, it
              > >> is perfect.
              > >> Now, we want to support the failover , load balancing ... (High
              > >Availability).
              > >>
              > >> I know, weblogic cluster supports HttpSessions, EjbObjects ... etc.
              > > What
              > >about
              > >> Application scope objects.
              > >> we are planning for weblogic server which supports the our requirements.
              > >>
              > >> If not, what is the solution to make it work by using Weblogic server.
              > >> for eg: I can give what type of application we are developing ---
              > >similar to
              > >> textchat.
              > >> our application is real time application.
              > >>
              > >
              > >
              

  • Application scope variables ... an easier way or not ?

    Instead of sharing application scope variables through the
              servletContext()/application I am using a normal singleton class (or maybe
              static class) to share all my application varaiable. It works fine and it
              takes a lot less code to write.
              It seamed logical to do this a static classes or singletons are shared
              within a single servletContext/application (which there seems to be only one
              per WL instance anyway). (singleton is quite nice pattern coz. all
              jsp:useBeans with the application scope are by definition singletons)
              Has anoyne tried something similar or maybe know of the problem with this
              approach. I assume that server will never reinitialise application level
              variables ...... hope the assumption is correct. ....
              

    When you specify application scope, the JSP stores/retrieves the value
              into/from the servlet context. You may already know this, but it sounded
              like what you thought you were somehow avoiding.
              Cameron Purdy
              http://www.tangosol.com
              "Bohinc D" <[email protected]> wrote in message
              news:[email protected]..
              > Instead of sharing application scope variables through the
              > servletContext()/application I am using a normal singleton class (or maybe
              > static class) to share all my application varaiable. It works fine and it
              > takes a lot less code to write.
              >
              > It seamed logical to do this a static classes or singletons are shared
              > within a single servletContext/application (which there seems to be only
              one
              > per WL instance anyway). (singleton is quite nice pattern coz. all
              > jsp:useBeans with the application scope are by definition singletons)
              >
              > Has anoyne tried something similar or maybe know of the problem with this
              > approach. I assume that server will never reinitialise application level
              > variables ...... hope the assumption is correct. ....
              >
              >
              >
              

  • Calling a method for application scope

    I have a method that initializes a hashtable.
    That method should be called once when my web app starts, I need to load that hashtable into memory so whenever a user needs a value from that hashtable, it readily access the hashtable and doesn't load it everytime it is called. How do I do that?

    Just put it in the application scope in the faces-config.xml?

  • Looking for best practice on application scope beans

    Hey – a portal newbie here. I’ve got some application scope beans that need to be initialized on startup. First thought was to create a servlet that would set the bean. Then I saw the GlobalApp setting, but I think that looks like it is more session scope than application… Looking to be corrected here if I am wrong.
    Is there a place where these type of things traditionally happen? Read only, so no cluster worries (I think) Using WLP 8.1 SP4 and looking for best practices. Thanks for the help!

    To support "code sharing" you need an integrated source code control system. Several options are out there but CVS (https://www.cvshome.org/) is a nice choice, and it's completely free and it runs on Windows, Linux, and most UNIX variants.
    Your next decision is on IDE and application server. These are usually from a single "source". For instance, you can choose Oracle's JDeveloper and Deploy to Oracle Application Server; or go with free NetBeans IDE and Jakarta Tomcat; or IBM's WebSphere and their application server. Selection of IDE and AppServer will likely result in heated debates.

  • Killing a bean with application scope?

    Is there any way to kill a bean with application scope?
    I am writing a web application, that most likely the browser window will never be closed. The problem is a user is authenticated onto our site but because the bean containing the users acct info is application scope, if another user logs in it still shows the old user as logged in. So on logout i would like to kill the application, the bean, servletContext...anything that will refresh the bean and the corresponding jsp. Any help is much appreciated.

    There is an indirect way if you know servlets. The "application" implicit object that you use in your JSP is the javax.servlet.ServletContext object. Instead of declaring your bean using the jsp:useBean tag, directly put your objects into the ServletContext using ServletContext.putAttribute() method. Objects put in the ServletCOntext are available to all pages in the application. Just use the ServletContext.getAttribute() method to retrieve this bean in any other page.
    To "kill the bean", just reset the value of this object to null by calling putAttribute(null).

  • Updating Beans in Application Scope

    The problem is that i dont know how to update a bean in an application scope:
    in EA4 i use this instruction to update a bean property:
    // get the faces context
    FacesContext facesContext = FacesContext.getCurrentInstance();
    // update a property in application scope
    (Util.getValueBinding("BeanName.propertyName")).
    setValue(facesContext,"text");
    and it worked ok in jsp:
    <h:output_text valueRef="BeanName.propertyName" />
    Now in version 1.0 i wrote:
    Application app = facesContext.getApplication();
    errorAplicacion = (ErrorAplicacion)app.createValueBinding("#{beanName}").
    getValue(facesContext);
    How should i update this value in application scope to be used in the jsp ?
    I use in jsp:
    <h:output_text value="#{BeanName.beanProperty}"/>
    But i receive in logs:
    Expression BeanName.beanProperty does not follow the syntax #{...}
    And the result is null
    Thanks a lot
    German

    If you are quoting your 1.0 code literally, you've got a case mismatch between "#{beanName}" when you create the value binding expression and "#{BeanName}" in the JSP page. As with most things in Java, the names are case sensitive.
    Craig McClanahan

  • 300 requests per hour reading from Application scope Good/Bad idea

    I am saving some html in application scope & reading with
    <cflock readonly.
    Will it be a problem if more than 5 requests are made per
    second?
    Does deadlocks occurs with readonly-cflock?
    Thanks

    While creating/changing application scope variables in a
    lock, I think there must be an exclusive lock. You must be careful
    not to set any shared variable such as application inside a read
    only cflock tag.
    I also would suggest to check the usage of Application.cfc
    and onApplicationStart method. You can set application default
    variables and constants in onApplicationStart method in your
    Application.cfc.

  • Application scope problem in a JSP

    Hi,
    I try to store an object with the following code :
    getServletContext().setAttribute("application", app);
    Later I want to access this object from a JSP with :
    <jsp:useBean id="application" scope="application" class="de.skillworks.SWApp"/>
    that dosn't work !? I can not debug my application because the jsp is initializing my app object new. When I try in my JSP :
    SWApp app = (SWApp)pageContext.getServletContext().getAttribute("application");
    it works fine. I get my object which I have store in my servlet.
    In a Tomcat environment my code is working just the Jdeveloper has a problem with it.
    null

    Andy -
    The web-to-go server has difficulty dealing with sessions. Testing in Tomcat is a good alternative, and this is resolved in Oracle9i JDeveloper.
    Hope this helps,
    Lynn

  • OC4J- NamingException: Not in an application scope

    I have a JMS program(ResourceAdapter) which I am deploying on OC4J 10g (10.0.3.0.0) .
    The program first creates InitialContext object and and then looks for the JMS connection factory and JMS queue in the "start" method of resource adapter. When I deploy this program everything works fine first, but later when I bounce oc4j, I start
    getting "javax.naming.NamingException: Not in an application scope"
    exception. Can someone suggest me what could be causing this?
    I have tried restarting the oc4j with userThreads option but it doesn't help.
    Program code:
    try{
    mContext = new InitialContext();
    System.out.println("**************1**********");
    mQueueCF =
    (QueueConnectionFactory)mContext.lookup("ojmsjra/MyQCF");
    System.out.println("**************2************");
    mQueue= (Queue)mContext.lookup("ojmsjra/QUEUE");
    System.out.println("**************3*********");
    }catch(Exception ex){
    ex.printStackTrace();
    After oc4j is restart only "**1**" gets printed and the following exception(lookup fails)
    04/09/27 15:56:15 javax.naming.NamingException: Not in an application scope - start Orion with the -userThreads switch if using user-created threads
    04/09/27 15:56:15 at com.evermind.server.PreemptiveApplicationContext.getContext(PreemptiveApplicationContext.java:29)
    04/09/27 15:56:15 at
    com.evermind.naming.FilterContext.lookup(FilterContext.java:127)
    04/09/27 15:56:15 at
    com.evermind.server.PreemptiveApplicationContext.lookup(PreemptiveApplicationContext.java:48)
    04/09/27 15:56:15 at
    javax.naming.InitialContext.lookup(InitialContext.java:347)
    04/09/27 15:56:15 at
    oracle.panama.messaging.driver.DriverResourceAdapter.<init>(DriverResourceAdapter.java:40)
    04/09/27 15:56:15 at
    sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    04/09/27 15:56:15 at
    sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
    04/09/27 15:56:15 at
    sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
    04/09/27 15:56:15 at
    java.lang.reflect.Constructor.newInstance(Constructor.java:274)
    04/09/27 15:56:15 at java.lang.Class.newInstance0(Class.java:306)
    04/09/27 15:56:15 at java.lang.Class.newInstance(Class.java:259)
    04/09/27 15:56:15 at
    com.evermind.server.connector.deployment.ConnectorArchive.createJavaBeanInstance(ConnectorArchive.java:462)
    04/09/27 15:56:15 at
    com.evermind.server.connector.deployment.ConnectorArchive.start(ConnectorArchive.java:360)
    04/09/27 15:56:15 at
    com.evermind.server.Application.initConnectors(Application.java:444)
    04/09/27 15:56:15 at
    com.evermind.server.Application.postInit(Application.java:681)
    04/09/27 15:56:15 at
    com.evermind.server.Application.setConfig(Application.java:201)
    04/09/27 15:56:15 at
    com.evermind.server.Application.setConfig(Application.java:170)
    04/09/27 15:56:15 at
    com.evermind.server.ApplicationServer.initializeApplications(ApplicationServer.java:1708)
    04/09/27 15:56:15 at
    com.evermind.server.ApplicationServer.setConfig(ApplicationServer.java:1412)
    04/09/27 15:56:15 at
    com.evermind.server.ApplicationServerLauncher.run(ApplicationServerLauncher.java:93)
    04/09/27 15:56:15 at java.lang.Thread.run(Thread.java:536)

    Gedomir,
    Thanks for the reply. But unfortunately it did not work. I was using the default initial context. I tried setting the properties as well. Even then it did not work.
    I am trying this with oc4j_extended.
    Thanks again.

  • Accessing Application Scope from an EJB

    I'm not sure of the best way of doing this:
    The set up:
    We have a rather large J2EE application that is composed of only servlets and JSPs at the moment (When the application began development EJB was in its infancy and not feasible for the development of the app). Some of the new deployments of the app involve distributed webserver over 4 JVMs and 2 machines. When a user connects the servers load balancing decides which particular JVM they should be connected to. We perform large data caching into the servlet application scope to avoid having to access the database every time a change is made by a user to certain tables in our database. The data caches are stored in hashtables in the servlet application scope.We seem to have no way to determine what other JVMs are running or which JVM a user is currently connected to.
    The problem:
    Apparently the application scope is for a particular JVM. This means that when a user makes a change to a data cache the change doesn't effect users in the other 3 JVMs of the application, only the users who, due to load balancing, happened to be connected to the same JVM as the one where the change was made.
    Our possible solution:
    We were thinking that we could set up a queue (such as MQSeries from IBM) and any time a change is made to one of these data caches put a message on the stack saying that the particular table had been updated. Then a MDB would be listening asynchronously and digest the message from the Queue and recache the tables from the database.
    So here are my questions:
    1. Would this work? Would putting a MDB in the EJB Container give each JVM the MDB in the first place, or would this mean it would pick one of the JVMs to deploy the MDB on and still not fix our problem.
    2. If this does work, how do I access the hashtables stored in the Servlet Application scope from the MDB. I can't seem to find any method available to the MDB (or any EJBs for that matter) that can access the servlets Application scope.
    3. Is this the best way to do this? Or is there a better way to share data between seperate JVMs that I don't have a URL to (It's all ambiguous and handled by the server as to which JVM actually gets the connection.)
    Just in case this is needed:
    We are running IBM WebSphere 5 Application Server and the database could be anything from DB2 to Oracle.
    Thanks in advance for any possible help.

    You wont get any api for directly accessing Servlet application objects from any ejb. I dont think MDB either solves your problem directly. Indirectly you can place a request to some servlet (should be there for each JVM and web application ) and update your application scope variable. I would suggest you to cache the data in database if the size of cache is large. otherwise any open caching tools may help you.

Maybe you are looking for

  • Can I change the File name of pics when capturing with iPhoto?

    Hi, I am a new user of Macbook and Mac OS, so, maybe this is a stupid issue. I have a sony cybershot and I was wondering if when I capture my pics from the camera with iPhoto I could change the name of the picture file?....or the filename will always

  • Accessing previous iTunes purchases in Snow Leopard

    I recently upgraded to Snow Leopard. Sparing you all the details, I am having to rebuild my iTunes Library from scratch, bringing it over from Time Machine is causing problems, basically, it causes my Time Machine backups to fail once I bring the old

  • Outlook Express - Color Selection

    Hello: I am using OE 5.0.7,I have deactivated all of the color selection controls in the Preferances. But when I get e-mails from organizations and or companies the message header shows up in a Maroon type color - the message it's self shows in black

  • Cannot start background process DTPR_13362_

    Hi ,     Whenever DTP  is executed  in the Dev Server,it throws an error. Error  msg: Cannot start background process DTPR_13362_1 26.09.2011 14:17:44 1 Min. 50 Sec. while checking the message in the monitor screen the cursor is at this function. CAL

  • No icon

    I installed Adobe Photoshop CS5 Extended but didn't get an icon and can't tell which of the files is supposed to be the program.