为什么tomcat最新代码在main方法中使用同步

时间:2018-10-25 02:54:00

标签: java tomcat source-code-protection

查看Tomcat的最新代码,找到主要方法,它在启动引导程序实例时使用同步。

synchronized (daemonLock) {
        if (daemon == null) {
            // Don't set daemon until init() has completed
            Bootstrap bootstrap = new Bootstrap();
            try {
                bootstrap.init();
            } catch (Throwable t) {
                handleThrowable(t);
                t.printStackTrace();
                return;
            }
            daemon = bootstrap;
        } else {
            // When running as a service the call to stop will be on a new
            // thread so make sure the correct class loader is used to
            // prevent a range of class not found exceptions.
            Thread.currentThread().setContextClassLoader(daemon.catalinaLoader);
        }
    } 

1 个答案:

答案 0 :(得分:0)

TL; DR:Mark Thomas减少了来自静态代码分析工具SpotBugs的警告消息。

正如您在Tomcat SVN日志中所见,同步是在修订版1826336中引入的:https://svn.apache.org/viewvc/tomcat/trunk/java/org/apache/catalina/startup/Bootstrap.java?r1=1826335&r2=1826336&

评论了Fix some more SpotBugs warnings

当在Bootstrap.java的修订版1826335上运行SpotBugs且所有模块均已激活且灵敏度/详细程度达到最高时,我可能会重现他已修复的警告:

Bug: Incorrect lazy initialization of static field Bootstrap.daemon in Bootstrap.main(String[])

This method contains an unsynchronized lazy initialization of a non-volatile static field. Because the compiler or processor may reorder instructions, threads are not guaranteed to see a completely initialized object, if the method can be called by multiple threads. You can make the field volatile to correct the problem. For more information, see the Java Memory Model web site. 

Rank: Of Concern (17), confidence: Low
Pattern: LI_LAZY_INIT_STATIC 
Type: LI, Category: MT_CORRECTNESS (Multithreaded correctness)