Clarify the situation with cleaning Spring Prototype- beans from memory

I would like to understand if I should clear the prototype beans from memory manually myself.

In the Spring documentation, you can see: "Client code needs to clean up objects with a prototype and release expensive resources that the bean (s) prototype supports.

So, from this, it seems to you that you should clean the beans prototype yourself.

However

I am using VisualVM memory profiler . I created some prototypes - beans. You can see 51 of them.

enter image description here

Then you can see the situation when the garbage collector clears the memory - the entire beans prototype is cleared .

enter image description here

So can anyone clarify the situation? The prototype-beans is successfully removed by the garbage collector, or should we clean them manually (if so, how)?


Addition. Some guys asked to show the prototype code - beans. In fact, I do not see any point in this, because in a specific example I create them only as a test, and this does not apply to the real situation with cleaning the beans prototype from memory. Developers can create beans prototypes in different ways, but their behavior in the future does not depend or does not depend on the method of creation.

, 400 , Prototype- beans, . , beans VisualVM, , beans .

, , , bean.

beans :

for(int i=0;i<10;i++){
        Prototype1 prototype1=applicationContext.getBean(Prototype1.class);
        Prototype2 prototype2=applicationContext.getBean(Prototype2.class);

        prototype1.test1();
        prototype2.test2();
}

bean:

@Service
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
public class Prototype1 {

    private int number;

    public Prototype1() {
        System.out.println("Prototype1 was created.");
    }

    public void test1(){

    }

}
+4
1

bean; .

bean, . bean bean , .

unit test , beans, .

, - , jvm beans.

 public class Example {

    @Scope("prototype")
    public static class SomePrototypeBean{

    }

    @Singleton
    public static class MySingleton{

        @Bean
        private SomePrototypeBean somePrototypeBean;

    }

    public static void main(String[] args){
       // context creation code goes here

       // singleton is created, a prototype injected
       context.getBean(MySingleton.class);
       // NOTE: the prototype injected will last for as long as MySingleton has reference
       // my singleton will exist for as long as the context has reference

       doStuff(context);
       //prototype bean created in the method above will be GCed
    }

    public static void doStuff(Context context){
        context.getBean(MyPrototypeBean.class);
        //since we literally are doing nothing with this bean, it will be 
        // marked for garbage collection
    }

}  
+1

Source: https://habr.com/ru/post/1679273/


All Articles