Question

The following class is not thread-safe (as proven in 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;
   }
}
Was it helpful?

Solution

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.

OTHER TIPS

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.

Although it has been long time since this question was asked or answered , today I came across this question while searching on google.

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?

www.contemplateltd.com , they have developed an advanced static analysis tool. But its not free.

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

http://www.checkthread.org/index.html , This is opensource project you may want to see examples here

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top