Home > Enterprise >  Garbage collector vs IOC
Garbage collector vs IOC

Time:03-21

Today I attend the interview I am a newbie to java, spring boot. The interviewer asked the question about garbage collectors. I said the garbage collector will release the unused resource. Then he asked about the IOC container, I said it take control of object creation and will inject into the dependent bean. Then he asked why we need to use an IOC container I said it will not create a new object every time it will use an existing one. Again he asked okay what is the issue in creating a new object because the garbage collector will release the memory then why should we go for IOC..? I am stuck here. Please help to understand this better

CodePudding user response:

In short, you don't always want new objects because they can be very expensive/slow to be created.

IOC container allows your component to give up control of how your dependencies are created and managed.

For example: If I create a DAO layer/class in traditional way, my DAO layer needs to know about how to create datasource. This can be managed, but imagine lot more classes that need to know now how to create a datasource.

Use IOC, you DAO layer will say: Hey ! I need an instance of datasource. Now, it is upto IOC container to find one and provide it for you. You still need to provide IOC a way to create this instance for you. But in this case, you all DAO layer can remain cohesive and just do what they should do - perform transactions. This will also allow you to create specialist classes / components that are responsible for handling database connectivity in specalized manner.

In spring, all beans are singleton by default. It means there would only be one instance in Spring context. You don't need them to be created multiple times.

Purpose of IOC is not to ease up functioning of GC. It is to let go of how your components and dependencies are created.

  • Related