I use spring boot at work, and DI (Dependency Injection), which is the heart of it, It uses the singleton design pattern, and by default only one instance is created. Even if I searched on the net, there was an article that seems to be buggy if I implement it so that it has a state with spring boot. Thinking about it, that? ?? ?? Only one instance can be created, but is it okay if simultaneous requests are made for one API? What's going on ?? ?? I thought. Maybe where is the memory allocation? Which period? I thought it was because I didn't understand it, so I reorganized it.
First, the memory area ・ Static area -Heap area -Stack area
Next, expand it to memory (mostly, so there are likely to be others).
Here is a table of each
So, when you think about it again, "don't have a state" means that if you implement it so that it has an instance variable, Since it is buggy, 5, 6 and 7 are expanded to the stack area as thread information of the request, so there is no worry about bugs.
Even if you look at the singleton design pattern again, it will come to your mind. Create only one instance as a global variable, and since it is a private variable, it will not be created again. By calling the getInstance () method, the address of the instance expanded in the heap area is returned. If you add @Bean, @Controller, @Service, @Component to each class with the annotation of spring boot, it seems that the behavior is like this internally.
singlton.java
public class Singlton{
private static Singlton singlton = new Singlton();
private Singlton(){}
public static Singlton getInstance(){
return singlton;
}
}
● If you compare it with Naruto ... Naruto (main body): Code information → I have various techniques. Naruto (Shadow Body): Object → The work to be done is different. If you don't release your body regularly, Naruto will run out of chakra (memory leak will occur, and garbage collection will erase objects regularly). Naruto (shadow alter ego) behavior: local variables, etc. → Actions such as throwing shuriken or using techniques.