TCS Papers: Sample Questions 342 - 342 of 502

Examrace Placement Series prepares you for the toughest placement exams to top companies.

Question number: 342

» Basic CS » Data Structures

Essay Question▾

Describe in Detail

What is lazy initialization?

Explanation

  • Lazy initialization is a process by which objects retrieved via a process or operation are not initialized (or instantiated) before the actual need to use them appears.

  • Prior to. NET 4.0, common example of lazy initialization was the singleton pattern:

Public class DataManager

  1. {
  2.     static Datamanger dm=null;
  3.     DataManager()
  4.     {
  5.     }
  6.     public static DataManager GetInstance()
  7.     {
  8.         if(dm== null)
  9.         {
  10.             Dm=new DataManager();
  11.         }
  12.         return dm;
  13.     }
  14. }
  • Here, lazy initialization is used when the DataManger instance is called.

  • If the existing instance is null, then a new instance is created. This example is however not thread safe –if the instance is evaluated in two or more threads, none of the other threads knows about the existing instance (initialized in one of the threads), so each one of them will create a separate, new instance.

  • In. NET 4.0, there is the Lazy < T > class that facilitates lazy initialization.

  • Applied to previous example, the DataManager class would use lazy initialization:

public class DataManager

  1. {
  2.     static Lazy<DataManagerdm=new Lazy<DataManager>(()=> new DataManager());
  3.     DataManager()
  4.     {
  5.     }
  6.     public static DataManager GetInstance()
  7.     {
  8.         return dm.Value;
  9.     }
  10. }
  • There is no DataManager instance in dm until dm. Value is called – only then an active instance of the class is created.

  • Lazy < T > is thread-safe, basically using “first come – first serve” principle - when a thread creates the instance, it will lock that specific instance and the same value will be available across all threads