How memory works in object-oriented languages

Why I decided to write an article

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.

Memory mechanism (Java-based)

First, the memory area ・ Static area -Heap area -Stack area

Next, expand it to memory (mostly, so there are likely to be others).

  1. Code information (class body)
  2. Global variables
  3. Instance
  4. Instance variable (specified by constructor)
  5. Local variables
  6. Arguments for each method
  7. Return value

Here is a table of each スクリーンショット 2020-06-20 21.57.09.png

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.

Rethink the singleton

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;
    }
}

Bonus: I thought about it in the world of NARUTO

● 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.

Conclusion: What is NARUTO ... object ninja !!!

Recommended Posts

How memory works in object-oriented languages
How Dispatcher servlet works in Spring MVC
How jul-to-slf4j works
Deep dive into how HashMap works in Java
How Docker works ~ Implement the container in 60 lines
Variadic arguments in various languages
[Java] How Spring DI works