Alex Rivera | Logout

Proving the following code not thread safe

Asked 2010-03-09T16:12:45.070
12

How can I quickly prove that the following class is not thread-safe (as it uses Lazy Initialization and not using synchronization) by writing some code ? In other words, if I am testing the following class for thread safety, how can I fail it?

public class LazyInitRace {
  private ExpensiveObject instance = null;

  public ExpensiveObject getInstance() {
     if (instance == null)
        instance = new ExpensiveObject();
    return instance;
  }
}
Edit
Report

1 Answer

0

Put a really long calculation in the constructor:

public ExpensiveObject()
{
    for(double i = 0.0; i < Double.MAX_VALUE; ++i)
    {
        Math.pow(2.0,i);
    }
}

You might want to decrease the termination condition to Double.MAX_VALUE/2.0 or divide by a larger number if MAX_VALUE is taking too long for your liking.

answered 2010-03-09T16:24:27.333

Your Answer