It's not a secret anymore!*
The moose likes Servlets and the fly likes will a bean with application scope be garbage collected Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Servlets
Bookmark "will a bean with application scope be garbage collected" Watch "will a bean with application scope be garbage collected" New topic
Author

will a bean with application scope be garbage collected

steve Barf
Greenhorn

Joined: Oct 15, 2004
Posts: 26
I am thinking of writing a bean to hold a quantity of database information to prevent every user of a web application having to retrieve all the data.



But I have a few concerns :
  • 1) what would stop this bean from being garbage collected ?
  • 2) what would be the best way to create the bean ?


  • something like this ? :
    [CODE}
    appBean myAppBean = (appBean) getServletContext().getAttribute("myAppBean");
    if (myAppBean==null)
    {
    appBean myAppBean = new appBean();
    myAppBean.getData();
    getServletContext().setAttribute("myAppBean");
    }
    [/CODE]
    and then reference it in jsp's by :

  • 3) should the bean be created as a singleton ?


  • Steve
    Ben Souther
    Sheriff

    Joined: Dec 11, 2004
    Posts: 13410

    Duplicate of:
    http://www.coderanch.com/t/360967/Servlets/java/will-bean-application-scope-garbage


    Java API J2EE API Servlet Spec JSP Spec How to ask a question... Simple Servlet Examples jsonf
    Ulf Dittmer
    Marshal

    Joined: Mar 22, 2005
    Posts: 41613
        
      55

    # 1) what would stop this bean from being garbage collected ?
    # 2) what would be the best way to create the bean ?
    # 3) should the bean be created as a singleton ?


    1) the fact that there is a live reference to it in the servlet context

    2 and 3) That code should be in the init method of a servlet that's defined to be loaded at startup time (via <load-on-startup> in web.xml). That way you don't need to get it and compare it to null - you just create it and store it.
    [ August 15, 2005: Message edited by: Ulf Dittmer ]

    Ping & DNS - my free Android networking tools app
    Ben Souther
    Sheriff

    Joined: Dec 11, 2004
    Posts: 13410

    Steve,
    Any time you accidentally create a duplicate thread, as seems to be the case here, please delete one of them. You now have slightly different answers in two different threads.
    [ August 15, 2005: Message edited by: Ben Souther ]
     
    I agree. Here's the link: http://aspose.com/file-tools
     
    subject: will a bean with application scope be garbage collected