Results 1 to 3 of 3

Thread: Does getBean() creates some garbage data

  1. #1
    Join Date
    Jan 2013
    Posts
    2

    Default Does getBean() creates some garbage data

    Hi,

    I have recently joined a new project and was surprised to see the bean management in the project. Though they use Spring for dependency injections , once the beans have been instantiated they create another map where they maintain a mapping :
    class type => bean reference
    In the application whenever a bean is needed, they do map.get(class type) rather than doing applicationcontext.getBean().

    The code comments say that this was done as spring's applicationcontext.getBean() creates a garbage data of 150KB per call. I looked at the code for getBean() method and couldn't understand why did the author think garbage will be created.

    This is code that creates the map :

    private static Map<Class, Object> beans = new HashMap<Class, Object>();
    public <T> T getBean(Class<T> clazz)
    {
    Object object = beans.get(clazz);
    if(object == null)
    {
    // Caching bean as spring get bean creates approx 150KB of garbage per call.
    object = appContext.getBean(clazz);
    beans.put(clazz, object);
    }
    return (T)object;
    }

    This didn't make any sense to me hence requesting the opinion of the experts on this matter.

    Best Regards

  2. #2
    Join Date
    Jun 2006
    Location
    The Netherlands
    Posts
    13,625

    Default

    Please use [ code][/code ] tags when posting code.

    In the application whenever a bean is needed, they do map.get(class type) rather than doing applicationcontext.getBean().
    IMHO you shouldn't be doing either of those but use dependeny injection to get access to your beans.

    The code comments say that this was done as spring's applicationcontext.getBean() creates a garbage data of 150KB per call. I looked at the code for getBean() method and couldn't understand why did the author think garbage will be created.
    Me neither so you might want to talk to the original author. The only thing I can think of is the use of prototype scoped beans which create a new instance each time you call getBean but that is the intent of prototype.
    Marten Deinum
    Java Consultant / Pragmatist / Open Source Enthousiast / Author


    Pro Spring MVC: With Web Flow
    Conspect

    Have you read the reference guide.
    Use the [ code ] tags, young padawan

  3. #3
    Join Date
    Jan 2013
    Posts
    2

    Default

    Thanks for your prompt response, Marten. Yes you are right this should only happen if the bean scope is prototype.

    Best Regards
    Madhulika

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •