Friday, 22 April 2016

When the Race condition occurs in Lazy initialization ?


Example : Lazy initialization in case of singleton implementation
public class Sample {
  private MyClass instance = null;

  public MyClass getInstance() {
      if (instance == null) {
           instance = new MyClass();
      }
      return instance;
  }
}

Suppose, Threads A and B execute getInstance at the same time.
A sees that instance is null and instantiates a new object.
B also checks if instance is null and the result depends on perfect timing including time for instantiation and assignment.

Ideally, getInstance supposed to return the same object every time.
But it may be possible to create two different object using new operator, which is a Race condition.
- similar to counter increment

No comments:

Post a Comment

Note: only a member of this blog may post a comment.