Saturday 13 February 2016

Secrets of Double Brace Initialization

What is Double Brace Initialization (DBI)? 
Using this feature we can create and initialize an object in a single line.
Confused ? Lets see a simple example : We have a requirement that to initialize all items of a vegetable shop with price.

Output:
Items available with Price :
{FRUITS={Apple=120, Grapes=80, Orange=40}, VEGETABLES={Potato=22, Onion=30, Tomato=60}}

This is how we normally do. And this needs 11 lines of code to create and initialize 3 maps.

Now We will re-write the same requirement using DBI feature and see how it is handy for developers.
Output: (Same as previous)
Items available with Price : 
{FRUITS={Apple=120, Grapes=80, Orange=40}, VEGETABLES={Potato=22, Onion=30, Tomato=60}}

Now See the Secret behind this :
Let see with a simple example with DBI.
Output:
edu.pk.core.DoubleBraceInitialization2$1

{Potato=22, Onion=30, Tomato=60}

We know that while using an anonymous class, compiler creates a separate .class file for the inner class of the enclosing class with the provided overriden method . In similar way, for this DBI feature also compiler creates a separate,class file for the inner class and directly copies the statements written inside {{  and }} and put into the constructor of the inner class.
In output, we can see it prints the class name as edu.pk.core.DoubleBraceInitialization2$1
And the inner class will be look like :
Observe here, the compiler just copied all lines written inside {{ and }} and put inside the constructor body.

So if we understand the secret behind, then now we can sure that we can instantiate and initialize the object our own class using DBI feature provided that class must have non-private constructor which we will use to instantiate the object. Because inheritance is not possible if super class has private construtor.

So it is cool, right? But wait a minute..... I want show something.
See here how many .class files are created while using DBI, for class DoubleBraceInitialization1.java. 1 for main class and 3 for inner classes for the map initialization. So imagine, how many class file it will create if we use such kind of code in our application. For each and every call to the method it will create all these files which is a burden for the class lodaer. Beacuse of this issue, it is not recomendade to use such type of initialization.

Warning:
Use of this can be lead to performance issue and memory leak problem.


Thank You for Visiting the blog. Please feel free to share yout comment/suggestion. 

No comments:

Post a Comment