Search code examples
javafindbugsthread-local

FindBugs warning on ThreadLocal init


I have ThreadLocal instance which was initialized with overridden initValue method. Also I have annotated it with @edu.umd.cs.findbugs.annotations.SuppressWarnings("SIC_INNER_SHOULD_BE_STATIC_ANON") as follows.

@edu.umd.cs.findbugs.annotations.SuppressWarnings("SIC_INNER_SHOULD_BE_STATIC_ANON")
private ThreadLocal<Integer> dbSwitchCount=new ThreadLocal<Integer>() {
    @Override 
    protected Integer initialValue() {
        return 0;
    }
};

Still Sonar report complains about "Performance - Could be re factored into a named static inner class". How can I make sure the above complain being ignored or what best way I can avoid that complain.


Solution

  • Do what Sonar suggests "Could be re factored into a named static inner class".

    Named static inner class:

    class MyClass {
        static class MyThreadLocal extends ThreadLocal<Integer> {
            @Override 
            protected Integer initialValue() {
                return 0;
            }
        }
        private ThreadLocal<Integer> dbSwitchCount = new MyThreadLocal();
    }
    

    I think the reason Sonar thinks that's a "Performance" improvement is because the anonymous class is non-static, and making it static improves memory management.