简体   繁体   中英

When does local variable of class annotated with @Component goes out of memory?

If I have a class annotated with @Component in spring boot application, and various threads are running on application and all are accessing on local variable of @Component class, will it be same variable or every thread will make it's own copy? How does @Component annotation really works and when does the local variable become empty? Let's say I have Set<String> in class, when will this set become empty?

@Component 
class testing {
  Set<String> localSet;
  Set<String> getString(){ return localSet;}
}

If I insert some random data in localSet, when will the data be deleted here?

I feel you are wondering about the "scope" of @Component as you mention that different threads will be accessing the same resource (In your case your classes' variables)

The default scope of @Component is singleton which as mentioned here in the docs is explained as

when you define a bean definition and it is scoped as a singleton, then the Spring IoC container will create exactly one instance of the object defined by that bean definition. This single instance will be stored in a cache of such singleton beans, and all subsequent requests and references for that named bean will result in the cached object being returned.

So in your case, Set<String> localSet; is initialized when the IOC container (application, generally) starts up and this same instance is used for different requests until the container shuts down. You can however change the scope of your component. More on scopes here .

@Component explained here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM