Leon Rosenberg wrote: > Hello, > > On Sun, Jun 14, 2009 at 7:01 PM, Jonathan > Mast<jhmast.develo...@gmail.com> wrote: >> I've not done anything with EJBs and I'm not sure what exactly you mean by >> static "properties". I have however dealt with reducing instantiations in >> servlets. I simply created a BeanBag class with static methods to each one >> of my beans; these are not "proper" beans, but where simply objects that >> were formerly used in JSP via the jsp:useBean directive. >> >> Here is the general pattern: >> >> class BeanBag { >> private static SomeBean someBean = null; >> >> public static synchronized getSomeBean() { >> if (someBean == null) someBean = new SomeBean(); >> return someBean; >> } >> } > > This is clearly the worst possible variant of doing it. Since > getSomeBean is called ALL the time and each call is synchronized you > are virtually giving up your concurrency and lining up all requests. > This will cause you serious headache as soon as the site becomes > decent traffic. > > There are at least two better ways to do it, static initizialization > and double checked locking (later only on post 1.5 vms). > 1. > class BeanBag { > private static final SomeBean someBean = new SomeBean(); > > public static SomeBean getSomeBean() { > return someBean; > } > } > > The difference is that the initialization happens at the loading time > of the class which is guaranteed be the jvm to be synchronized > (executed only by one thread) so there will be only one instance of > someBean and it will be available at first call to getSomeBean.
This variation is useful, if the goal is the Singleton pattern. http://en.wikipedia.org/wiki/Initialization_on_demand_holder_idiom p > 2. DLC - double checked locking, this is a very powerful but > hot-discussed pattern, useful if the instantiation of someBean is > really costly and you want to postpone it until it really needed. In > this case: > class BeanBag { > private static volatile SomeBean someBean = null; > > public static SomeBean getSomeBean() { > if (someBean==null){ > synchronized(BeanBag.class){ > if (someBean==null){ > someBean = new SomeBean(); > } > } > } > return someBean; > } > } > > >> I have now numerous Servlets, JSPs and POJOs that use BeanBag to obtain >> singleton instances of my beans. Its worked great for me. > > yet :-) > > regards > Leon > > --------------------------------------------------------------------- > To unsubscribe, e-mail: users-unsubscr...@tomcat.apache.org > For additional commands, e-mail: users-h...@tomcat.apache.org > > --------------------------------------------------------------------- To unsubscribe, e-mail: users-unsubscr...@tomcat.apache.org For additional commands, e-mail: users-h...@tomcat.apache.org