开发者

Thread Safety framework

开发者 https://www.devze.com 2022-12-23 01:31 出处:网络
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

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;
   }
}


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消