views:

96

answers:

2

Hi,

The following class is not thread-safe (as proven in http://stackoverflow.com/questions/2410499/proving-the-following-code-not-thread-safe )

Is there a framework out there that can help with either compile time / run time analysis and tell us that the following is not thread safe?

For compile time, ideally in Eclipse the wiggly underline comes up and tells us that the class is not thread safe?

For run time, will any the static code analysis catch the class as non-thread-safe?

public class LazyInitRace {
   private ExpensiveObject instance = null;

    public ExpensiveObject getInstance() {
    if (instance == null)
      instance = new ExpensiveObject();
    return instance;
   }
}
A: 

This is a classic problem called the double checked locking problem.

The problem is that you have a race condition because your check on whether instance is null and assigning the value. One solution to this problem that I like in Java is:

public class LazyInitRace {
  private static class Container {
    public final static ExpensiveObject INSTANCE = new ExpensiveObject();
  }

  public ExpensiveObject getInstance() {
    return Container.INSTANCE;
  }
}

The way this works is that the inner class isn't initialized until it's referenced (which gets you your lazy loading) and loading the class is an atomic and threadsafe operation.

There are however other valid solutions.

cletus
This is not double checked locking. Read the article you linked more carefully...
Steven Schlansker
+2  A: 

FindBugs can find parts of your code where thread synchronization is inconsistent, i.e. you synchronize access to a field in one place but not in another. It can also do basic validation against JCIP annotations, but I believe only @Immutable is checked at the moment.

I don't know of any static analysis tool that would automatically catch this particular case but I'm sure one exists.

Martin
FindBugs has a whole "Multithreaded Correctness" category.
Stephen Denne
I suppose FindBugs is the best option at this moment.
portoalet