[Java] Memory mechanism in object-oriented languages

2 minute read

Why I decided to write an article

I use spring boot at work, and at its core DI (Dependency Injection), According to the singleton design pattern, only one instance is created by default. Even if I checked it on the net, I found an article that seems to be buggy if I implement it so that it has a state with spring boot. Thinking about it, that? ? ? I can only create one instance, but is it okay if there are simultaneous requests for one API? What’s going on ? ? I thought. Maybe where is the memory allocation? What period? I thought that was because I did not understand it, so I arranged it again.

Memory mechanism (Java based)

First, the memory area ・Static area

  • Heap area ・Stack area

Then, expand it to memory (most likely, so there are others)

  1. Code information (class body)
  2. Global variables
  3. Instance
  4. Instance variable (specified in the constructor)
  5. Local variables
  6. Argument of each method
  7. Return value

Here is a summary of each ![Screenshot 2020-06-20 21.57.09.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/324175/b7e57227-d139-c03c-e175-(12975110e34f.png)

So, if you think again, “Do not have a state” means that if you implement it with instance variables, Since it is a bug, 5, 6, 7 are expanded in the stack area as the thread information of the request, so there is no worry of a bug.

Think singleton again

Even if you look at the design pattern of the singleton again, you can quickly feel it. Only one instance is created as a global variable, and it is a private variable so it will not be created again. The address of the instance expanded in the heap area is returned by calling the getInstance() method. When @Bean, @Controller, @Service and @Component are assigned 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 the world of NARUTO

●When compared to NARUTO… Naruto (body): Code information → Have various techniques. Naruto: Object →The jobs they do are different. If you don’t release your body regularly, Naruto’s body will run out of chakra (a memory leak occurs, a regular garbage collection is a garbage collection). Naruto (shadow alter ego) actions: local variables, etc. →Throwing a shuriken or using a technique.

Conclusion: What is NARUTO… object ninja!!!